Skip to content

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

release: v1.1.2 — schema-driven channels, secret masking, RAG simplification, KB-consistency hardening

Bingxi Zhao (Frank)100576da694d
diff --git a/.gitignore b/.gitignore
index 5b8827176..9bd7bf12c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,13 +5,13 @@
# ============================================
# User Generated Data and Outputs
# ============================================
-CLAUDE.md
# Runtime data (knowledge bases, tutorbot workspaces, memory, etc.)
data/
run_code_workspace/
deeptutor/agents/question/reference_papers/
deeptutor/services/rag/eg_only_for_analysis/
-DeepTutor_arxiv-4/
+docs/
+.github
# LaTeX build artifacts
*.aux
diff --git a/README.md b/README.md
index 9438992c2..de230ee73 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,8 @@
### 📦 Releases
+> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Schema-driven TutorBot Channels tab covering every built-in/plugin channel with per-field secret reveal, end-to-end channel secret masking with `?include_secrets=true` opt-in, concurrent `reload_channels` lock + 422 validation on bad channel config, RAG service collapsed to a single LlamaIndex pipeline (~2.6k lines of stale scaffolding removed), centralized `FileTypeRouter`, defensive RAG/KB consistency normalization across `deep_solve` / `deep_research` / `SolveToolRuntime` / `ResearchPipeline` / `DecomposeAgent` (no more phantom `DE-all` / `ai_textbook` fallbacks), externalized `agentic_chat.yaml` prompts, Thai README, and 6 new test modules.
+
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — Universal "Answer now" escape hatch across every capability, Co-Writer resizable split with line-anchored scroll sync, Save-to-Notebook message-selection mode, real notebook system adoption across Knowledge/Guide/Save flows, unified collapsible settings panel, dedicated streaming Stop button, TutorBot config manager refactor with atomic writes, light/Snow theme refresh, and expanded test suite.
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX block math parsing overhaul, LLM diagnostic probe agents.yaml configuration, extra headers forwarding in LLM factory, SaveToNotebookModal UUID fix, Docker + local LLM guidance, and expanded test suite.
diff --git a/assets/releases/ver1-1-2.md b/assets/releases/ver1-1-2.md
new file mode 100644
index 000000000..1ba05ee49
--- /dev/null
+++ b/assets/releases/ver1-1-2.md
@@ -0,0 +1,62 @@
+# DeepTutor v1.1.2 Release Notes
+
+**Release Date:** 2026.04.18
+
+## Highlights
+
+### TutorBot — Schema-Driven Channels Tab, Token Reveal & API-Side Channel Reload (#338)
+Replaced the hard-coded Telegram-only Channels tab in `web/app/(workspace)/agents/page.tsx` with a generic, schema-driven editor that works for **every** built-in or plugin channel without any per-channel front-end code. A new `GET /api/v1/tutorbot/channels/schema` endpoint introspects every discovered `XxxChannel` / `XxxConfig` pair (Telegram, Slack, Discord, Matrix, WhatsApp, Email, Feishu, WeCom, QQ, DingTalk, etc.) and ships back a flattened JSON-Schema payload (`$ref`s inlined), the default config, the channel's `display_name`, and a list of dot-paths for any string field whose name hints at a secret (`token`, `secret`, `password`, `api_key`, `encrypt_key`). The new `SchemaField` React component recursively renders the schema — booleans become checkboxes, enums become selects, string-arrays become one-per-line textareas, nested `Optional[Model]` becomes inline fieldsets, and any flagged secret renders as a `password` input with an inline eye-toggle (`Eye` / `EyeOff`) for explicit reveal. The Channels tab now also surfaces a `last_reload_error` banner so users immediately see when on-disk config and live listeners have diverged.
+
+### Channel Secret Masking End-to-End
+Added `mask_channel_secrets` and `_is_secret_field` helpers to `TutorBotManager` and rewired `TutorBotInstance.to_dict` with three explicit modes: list-of-channel-names (default for the `GET /tutorbot` index), nested dict with `***` masks (default for `GET /tutorbot/{bot_id}`), and full plaintext only when the caller passes `?include_secrets=true` (used exclusively by the admin edit form). `POST /tutorbot` and `PATCH /tutorbot/{bot_id}` responses are likewise masked. A new `tests/services/tutorbot/test_channel_secrets.py` (223 lines) and `tests/api/test_tutorbot_channel_schema.py` (185 lines) pin the masking rules, snake-case property names, secret-field detection (deliberately excluding non-string fields like `user_token_read_only: bool`), and the schema-endpoint shape across every built-in channel.
+
+### TutorBot — Concurrent Reload Lock & 422 on Bad Channel Config
+`PATCH /tutorbot/{bot_id}` now validates `payload.channels` against `ChannelsConfig` at the API boundary and returns a structured 422 (`{message, errors}`) instead of letting the bad config slip through to disk and blow up later inside `reload_channels`. `reload_channels` itself was hardened: a per-instance `asyncio.Lock` serialises concurrent invocations to prevent duplicate listeners, channel-manager construction was extracted into a shared `_build_channel_manager` so `start_bot` and `reload_channels` produce identical behaviour, and any teardown/rebuild failure is captured into `instance.last_reload_error` (cleared on the next success) and surfaced via the API.
+
+### RAG Service — One Backend, One Pipeline
+Removed ~2 600 lines of stale RAG scaffolding (`deeptutor/services/rag/components/{base,routing,chunkers,embedders,indexers,parsers,retrievers}/*`, `services/rag/pipeline.py`, `services/rag/types.py`, `services/rag/utils/__init__.py`, `services/rag/parsers/__init__.py`) that had been carrying placeholders for never-shipped pipelines. The factory (`services/rag/factory.py`) now exposes a single `LlamaIndexPipeline` keyed by `kb_base_dir`, and `RAGService` was simplified to a thin facade over it. `normalize_provider_name`, `LEGACY_PROVIDER_ALIASES`, `has_pipeline`, and the `_validate_registered_provider` API handler are all gone — `rag_provider` is now a stub field that silently coerces any legacy value (`lightrag`, `raganything`, …) into `llamaindex` while flagging the KB for re-indexing.
+
+### Centralized File Type Routing
+Extracted file-type classification into a single `deeptutor/services/rag/file_routing.py` module (`FileTypeRouter`, `DocumentType`, `FileClassification`) with a flat per-extension API: `get_document_type`, `classify_files`, `read_text_file`, `needs_parser`, `is_text_readable`, `get_supported_extensions`, `get_glob_patterns`. The provider-keyed variants (`get_extensions_for_provider`, `get_glob_patterns_for_provider`) have been removed since there is only one provider; every call-site (`knowledge/initializer.py`, `knowledge/manager.py`, `api/routers/knowledge.py`, `services/rag/pipelines/llamaindex.py`, `deeptutor_cli/kb.py`) now uses the flat helpers. Unknown extensions still fall through to a content-sniff (binary check + UTF-8 probe) before being marked `UNKNOWN`.
+
+### RAG/KB Consistency — No Phantom Knowledge Bases
+Closed every code path that could quietly invoke RAG against a non-existent or placeholder knowledge base:
+
+- **`deep_solve`** strips `rag` from the effective tool set when no KB is attached and emits a `trace_kind=warning` progress event so the UI can explain why retrieval was disabled.
+- **`deep_research`** drops `kb` from `request_config.sources` when no KB is attached, emits a warning, and surfaces a hard error if downgrading leaves the sources list empty (so the run aborts cleanly instead of producing an empty report).
+- **`SolveToolRuntime.execute("rag", kb_name=None)`** short-circuits with a structured `ToolResult(success=False, metadata={"skipped": True, "reason": "no_kb_selected"})` and never forwards to the registry, keeping the ReAct loop alive with a clear observation.
+- **`ResearchPipeline._call_tool`** for `rag` / `rag_hybrid` / `rag_naive` returns a structured `status: skipped` JSON (with a matching `tool_result` trace event) when `kb_name` is missing, instead of falling back to the old `DE-all` placeholder. Unknown tool types now return a structured `status: failed, reason: unknown_tool` instead of silently retrying RAG.
+- **`DecomposeAgent`** drops the `ai_textbook` default and disables RAG defensively when no `kb_name` is provided, even when the runtime config still says `enable_rag: True`.
+
+A new `tests/capabilities/test_rag_consistency.py` (233 lines) and `tests/agents/research/test_research_pipeline_rag.py` (146 lines) lock in the contracts end-to-end.
+
+### Agentic Chat Pipeline — Externalized Prompts
+Extracted every hard-coded zh/en string out of `deeptutor/agents/chat/agentic_pipeline.py` (337 → 108 lines, –68%) into two new YAML files: `deeptutor/agents/chat/prompts/{zh,en}/agentic_chat.yaml` (178 lines each). Stage labels, `kb_hint` injection, the thinking / acting / observing / responding system + user templates, and all UI-visible notices (no-tools, ReAct fallback, etc.) are now editable copy without a code change. Loaded via the existing `get_prompt_manager()` plumbing with a graceful fallback to `_text(zh=, en=)` if the YAML is missing.
+
+### Thai README (#337)
+Added a Thai-language README (`README_TH.md`) and wired it into the language switcher in the main README header.
+
+### Bug Fixes
+- **Research pipeline crashed when no KB was selected** — `rag_cfg.get("kb_name", "DE-all")` was falling back to a hard-coded knowledge base name that no longer exists in most installs, surfacing as `KnowledgeBaseNotFoundError` partway through a research run. Now short-circuits with a structured skip event.
+- **Decompose agent attempted RAG against a non-existent default KB** — `kb_name="ai_textbook"` was the constructor default; replaced with `None` plus a defensive `enable_rag = False` guard.
+- **Bad channel config silently persisted on disk and blew up at next bot start** — `PATCH /tutorbot/{bot_id}` now rejects with a 422 listing the validation errors before anything reaches `_save_bot_config`.
+- **Concurrent `reload_channels` could spin up duplicate listeners** — serialised via `instance.reload_lock`; failure leaves the bot running channel-less with `last_reload_error` set instead of in an inconsistent half-rebuilt state.
+- **Channel tokens leaked through `GET /api/v1/tutorbot/{bot_id}` and the create/patch responses** — secrets are now masked unless the caller explicitly opts in via `?include_secrets=true`.
+
+### Test Suite Expansion
+Added 6 new test modules covering the v1.1.2 surface area:
+
+- `tests/services/rag/test_file_routing.py` (108 lines) — extension classification (case-insensitive), unknown-extension content sniffing (text vs. binary), `read_text_file` encoding fallback chain, `classify_files` bucketing, and the helper getters.
+- `tests/services/config/test_knowledge_base_config.py` (147 lines) — pins the stub-provider contract: any legacy or unknown `rag_provider` value coerces to `llamaindex` and the on-disk migration flips legacy KBs to `needs_reindex: true`.
+- `tests/api/test_tutorbot_channel_schema.py` (185 lines) — `resolve_config_model`, `inline_refs` (with nested `$defs`), `collect_secret_fields` (string-only secret detection), and the `GET /api/v1/tutorbot/channels/schema` integration shape across telegram / slack / discord.
+- `tests/services/tutorbot/test_channel_secrets.py` (223 lines) — `mask_channel_secrets` deep-walk semantics for nested objects, lists, tuples, multiple email/slack secret keys, and the three `to_dict` modes (default = list, mask, include).
+- `tests/capabilities/test_rag_consistency.py` (233 lines) — `deep_solve` and `deep_research` strip `rag` / `kb` when no KB is attached, emit the right warning events, and (for research) surface a hard error if sources go empty.
+- `tests/agents/research/test_research_pipeline_rag.py` (146 lines) — pins the removal of the `DE-all` fallback in `ResearchPipeline._call_tool` and `DecomposeAgent`'s defensive RAG disablement.
+
+Extended `tests/agents/solve/test_tool_runtime.py` with two new cases for the `rag`-without-`kb_name` short-circuit (both `None` and empty string), `tests/api/test_knowledge_router.py` to flip the legacy "reject unsupported provider" tests into "coerce to llamaindex" tests, `tests/api/test_tutorbot_router.py` with the secret-handling cases for the stopped-bot GET route, and `tests/services/rag/test_rag_pipelines.py` + `tests/tools/test_rag_tool.py` to track the components → `file_routing` move.
+
+## Community Contributions
+
+- **@DoctorNasa** — Add Thai README documentation (#337)
+
+**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.1.1...v1.1.2
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 26a44eda3..48cc13a90 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -21,6 +21,7 @@ from deeptutor.core.trace import (
new_call_id,
)
from deeptutor.runtime.registry.tool_registry import get_tool_registry
+from deeptutor.services.prompt import get_prompt_manager
from deeptutor.services.llm import (
clean_thinking_tags,
complete as llm_complete,
@@ -67,6 +68,20 @@ class AgenticChatPipeline:
self.api_version = getattr(self.llm_config, "api_version", None)
self.registry = get_tool_registry()
self._usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "calls": 0}
+ # Prompts live in deeptutor/agents/chat/prompts/{zh,en}/agentic_chat.yaml
+ # so all user-visible / LLM-facing copy is editable without touching code.
+ try:
+ self._prompts: dict[str, Any] = (
+ get_prompt_manager().load_prompts(
+ module_name="chat",
+ agent_name="agentic_chat",
+ language=self.language,
+ )
+ or {}
+ )
+ except Exception as exc:
+ logger.warning("Failed to load agentic_chat prompts: %s", exc)
+ self._prompts = {}
def _accumulate_usage(self, response: Any) -> None:
usage = getattr(response, "usage", None)
@@ -161,7 +176,7 @@ class AgenticChatPipeline:
trace_meta = build_trace_metadata(
call_id=new_call_id("chat-thinking"),
phase="thinking",
- label=self._text(zh="Reasoning", en="Reasoning"),
+ label=self._t("labels.reasoning", default="Reasoning"),
call_kind="llm_reasoning",
trace_id="chat-thinking",
trace_role="thought",
@@ -177,10 +192,14 @@ class AgenticChatPipeline:
{"trace_kind": "call_status", "call_state": "running"},
),
)
+ thinking_user = self._t(
+ "thinking.user",
+ user_message=context.user_message,
+ )
messages = self._build_messages(
context=context,
system_prompt=self._thinking_system_prompt(enabled_tools, context),
- user_content=context.user_message,
+ user_content=thinking_user or context.user_message,
)
messages, images_stripped = self._prepare_messages_with_attachments(
messages,
@@ -226,10 +245,7 @@ class AgenticChatPipeline:
async with stream.stage("acting", source="chat"):
if not enabled_tools:
await stream.progress(
- self._text(
- zh="当前没有启用任何工具,本轮跳过工具调用。",
- en="No tools are enabled for this turn, so tool execution was skipped.",
- ),
+ self._t("notices.no_tools_enabled"),
source="chat",
stage="acting",
)
@@ -244,10 +260,7 @@ class AgenticChatPipeline:
)
await stream.progress(
- self._text(
- zh="当前模型不支持原生工具调用,已切换到 ReAct 文本编排。",
- en="The current model does not support native tool calling, so ReAct text orchestration is used.",
- ),
+ self._t("notices.react_fallback_switch"),
source="chat",
stage="acting",
)
@@ -269,7 +282,7 @@ class AgenticChatPipeline:
trace_meta = build_trace_metadata(
call_id=new_call_id("chat-observing"),
phase="observing",
- label=self._text(zh="Observation", en="Observation"),
+ label=self._t("labels.observation", default="Observation"),
call_kind="llm_observation",
trace_id="chat-observing",
trace_role="observe",
@@ -285,17 +298,7 @@ class AgenticChatPipeline:
{"trace_kind": "call_status", "call_state": "running"},
),
)
- observation_prompt = self._text(
- zh=(
- "请整理本轮推理与工具执行得到的关键信息,输出给 tutor 自己看的观察总结。"
- "聚焦:已确认事实、仍不确定的点、最终回答应强调什么。不要直接写给学生。"
- ),
- en=(
- "Summarize what was learned from the reasoning and tool execution for the tutor's internal observation note. "
- "Focus on confirmed facts, remaining uncertainty, and what the final answer should emphasize. "
- "Do not address the student directly."
- ),
- )
+ observation_prompt = self._t("observing.user_intro")
messages = self._build_messages(
context=context,
system_prompt=self._observing_system_prompt(enabled_tools),
@@ -340,7 +343,7 @@ class AgenticChatPipeline:
trace_meta = build_trace_metadata(
call_id=new_call_id("chat-responding"),
phase="responding",
- label=self._text(zh="Final response", en="Final response"),
+ label=self._t("labels.final_response", default="Final response"),
call_kind="llm_final_response",
trace_id="chat-responding",
trace_role="response",
@@ -356,20 +359,11 @@ class AgenticChatPipeline:
{"trace_kind": "call_status", "call_state": "running"},
),
)
- user_prompt = self._text(
- zh=(
- f"用户问题:\n{context.user_message}\n\n"
- f"{self._labeled_block('Observation', observation)}\n\n"
- f"{self._labeled_block('Tool Trace', self._format_tool_traces(tool_traces))}\n\n"
- "请基于以上内容,直接给出正式回答。不要暴露内部 pipeline、thinking、observing 等字样。"
- ),
- en=(
- f"User request:\n{context.user_message}\n\n"
- f"{self._labeled_block('Observation', observation)}\n\n"
- f"{self._labeled_block('Tool Trace', self._format_tool_traces(tool_traces))}\n\n"
- "Use this material to produce the final answer for the user. "
- "Do not mention the internal pipeline, thinking, or observing stages."
- ),
+ user_prompt = self._t(
+ "responding.user",
+ user_message=context.user_message,
+ observation=observation.strip() if observation.strip() else "(empty)",
+ tool_trace=self._format_tool_traces(tool_traces),
)
messages = self._build_messages(
context=context,
@@ -430,23 +424,11 @@ class AgenticChatPipeline:
).strip()
partial_response = str(answer_now_context.get("partial_response") or "").strip()
trace_summary = self._format_answer_now_events(answer_now_context.get("events"))
- user_prompt = self._text(
- zh=(
- f"用户原始问题:\n{original_user_message}\n\n"
- f"{self._labeled_block('Current Draft', partial_response)}\n\n"
- f"{self._labeled_block('Execution Trace', trace_summary)}\n\n"
- "请基于当前已经完成的内容,立刻直接生成给用户的最终答复。"
- "不要继续规划或调用工具,不要提到内部阶段。"
- "如果信息仍有缺口,请诚实说明不确定之处,但仍尽可能先给出当前最有用的回答。"
- ),
- en=(
- f"Original user request:\n{original_user_message}\n\n"
- f"{self._labeled_block('Current Draft', partial_response)}\n\n"
- f"{self._labeled_block('Execution Trace', trace_summary)}\n\n"
- "Using only the material already gathered so far, produce the final user-facing answer now. "
- "Do not continue planning or call tools, and do not mention internal stages. "
- "If something is still uncertain, be explicit about the uncertainty while still giving the most useful answer you can."
- ),
+ user_prompt = self._t(
+ "answer_now.user",
+ original_user_message=original_user_message,
+ partial_response=partial_response.strip() if partial_response.strip() else "(empty)",
+ trace_summary=trace_summary,
)
messages = self._build_messages(
context=context,
@@ -494,7 +476,7 @@ class AgenticChatPipeline:
trace_meta = build_trace_metadata(
call_id=new_call_id("chat-acting"),
phase="acting",
- label=self._text(zh="Tool call", en="Tool call"),
+ label=self._t("labels.tool_call", default="Tool call"),
call_kind="tool_planning",
trace_id="chat-acting",
trace_role="tool",
@@ -535,10 +517,7 @@ class AgenticChatPipeline:
if not raw_tool_calls:
await stream.progress(
- self._text(
- zh="本轮不需要调用工具。",
- en="No tool call was needed for this turn.",
- ),
+ self._t("notices.no_tool_call_needed"),
source="chat",
stage="acting",
metadata=merge_trace_metadata(trace_meta, {"trace_kind": "progress"}),
@@ -557,12 +536,10 @@ class AgenticChatPipeline:
pending_calls: list[tuple[str, str, dict[str, Any]]] = []
if len(raw_tool_calls) > MAX_PARALLEL_TOOL_CALLS:
await stream.progress(
- self._text(
- zh=f"模型请求了 {len(raw_tool_calls)} 个工具,本轮最多并行执行 {MAX_PARALLEL_TOOL_CALLS} 个,已截断。",
- en=(
- f"The model requested {len(raw_tool_calls)} tools. "
- f"At most {MAX_PARALLEL_TOOL_CALLS} can run in parallel in one turn, so the list was truncated."
- ),
+ self._t(
+ "notices.too_many_tool_calls",
+ requested=len(raw_tool_calls),
+ limit=MAX_PARALLEL_TOOL_CALLS,
),
source="chat",
stage="acting",
@@ -674,14 +651,8 @@ class AgenticChatPipeline:
control_actions=[
{
"name": "done",
- "when_to_use": self._text(
- zh="当已有信息足够,且不需要继续调用工具时使用。",
- en="Use when the available information is sufficient and no more tools are needed.",
- ),
- "input_format": self._text(
- zh="空字符串。",
- en="Empty string.",
- ),
+ "when_to_use": self._t("react_fallback.done_when_to_use"),
+ "input_format": self._t("react_fallback.done_input_format"),
}
],
)
@@ -689,7 +660,7 @@ class AgenticChatPipeline:
trace_meta = build_trace_metadata(
call_id=new_call_id("chat-react"),
phase="acting",
- label=self._text(zh="Tool call", en="Tool call"),
+ label=self._t("labels.tool_call", default="Tool call"),
call_kind="tool_planning",
trace_id="chat-react",
trace_role="tool",
@@ -747,10 +718,7 @@ class AgenticChatPipeline:
metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_output"}),
)
await stream.progress(
- self._text(
- zh="本轮不需要调用工具。",
- en="No tool call was needed for this turn.",
- ),
+ self._t("notices.no_tool_call_needed"),
source="chat",
stage="acting",
metadata=merge_trace_metadata(trace_meta, {"trace_kind": "progress"}),
@@ -805,10 +773,7 @@ class AgenticChatPipeline:
metadata = result["metadata"]
except Exception:
logger.error("Fallback tool %s failed", action, exc_info=True)
- result_text = self._text(
- zh=f"执行工具 {action} 时发生未知错误。",
- en=f"An unknown error occurred while executing {action}.",
- )
+ result_text = self._t("notices.tool_unknown_error", tool=action)
success = False
sources = []
metadata = {"error": result_text}
@@ -979,7 +944,7 @@ class AgenticChatPipeline:
if stream is not None and retrieve_meta is not None:
query = str(retrieve_meta.get("query") or tool_args.get("query") or "").strip()
await stream.progress(
- f"Query: {query}" if query else self._text(zh="开始检索", en="Starting retrieval"),
+ f"Query: {query}" if query else self._t("notices.start_retrieval"),
source="chat",
stage="acting",
metadata=derive_trace_metadata(
@@ -1006,11 +971,7 @@ class AgenticChatPipeline:
),
)
return {
- "result_text": result.content
- or self._text(
- zh="工具执行完成,但没有返回文本内容。",
- en="The tool completed without returning text output.",
- ),
+ "result_text": result.content or self._t("notices.empty_tool_result"),
"success": result.success,
"sources": result.sources,
"metadata": result.metadata,
@@ -1074,7 +1035,7 @@ class AgenticChatPipeline:
return derive_trace_metadata(
trace_meta,
call_id=new_call_id(f"chat-retrieve-{tool_index + 1}"),
- label=self._text(zh="Retrieve", en="Retrieve"),
+ label=self._t("labels.retrieve", default="Retrieve"),
call_kind="rag_retrieval",
trace_role="retrieve",
trace_group="retrieve",
@@ -1137,58 +1098,15 @@ class AgenticChatPipeline:
format="aliases",
language=self.language,
)
- return self._text(
- zh=(
- "你是 DeepTutor 的工具调用代理。你的任务是根据用户问题和前序 thinking,"
- "从当前已启用的工具中自主选择必要工具并调用。"
- "\n\n规则:\n"
- "1. 先完整审视所有已启用工具,再决定最有帮助的工具组合;不要只盯住单个工具。\n"
- "2. 对于需要定义、事实核验、外部资料、论文、计算、推理等不同信息面的复杂问题,优先并行调用多个互补工具来覆盖这些信息面。\n"
- "3. 只调用真正有帮助的工具,但只要工具能显著提升答案质量,就应充分调用。\n"
- "4. 参数要具体、可执行,优先使用用户原问题中的关键信息,必要时针对不同工具改写成最适合它的查询。\n"
- "5. 如果信息已经足够,可以不调用工具。\n"
- "6. 不要输出最终回答给学生;这里只负责工具选择与调用。\n"
- f"7. 单轮最多并行调用 {MAX_PARALLEL_TOOL_CALLS} 个工具;如果有多个互补工具都相关,优先在同一轮一起调用。\n\n"
- f"当前可用工具:\n{tool_list or '- 无'}\n\n"
- f"工具使用提示:\n{tool_aliases or '- 无'}"
- ),
- en=(
- "You are DeepTutor's tool-using agent. Based on the user request and prior thinking, "
- "autonomously choose and call only the enabled tools that are truly helpful."
- "\n\nRules:\n"
- "1. Review the full enabled tool list before deciding; do not fixate on a single tool too early.\n"
- "2. For complex questions that need definitions, grounding, outside evidence, papers, calculation, or deeper reasoning, prefer calling multiple complementary tools in parallel so each one covers a distinct information need.\n"
- "3. Call tools only when they add value, but when they materially improve answer quality you should use them fully.\n"
- "4. Use concrete, executable arguments grounded in the user's request, and adapt the wording when different tools need different query styles.\n"
- "5. If enough evidence already exists, you may skip tool use.\n"
- "6. Do not produce the final student-facing answer here; this stage is only for tool use.\n"
- f"7. At most {MAX_PARALLEL_TOOL_CALLS} tools may run in parallel in one turn; if several complementary tools are relevant, prefer issuing them together in the same turn.\n\n"
- f"Enabled tools:\n{tool_list or '- none'}\n\n"
- f"Tool usage notes:\n{tool_aliases or '- none'}"
- ),
+ return self._t(
+ "acting.system",
+ tool_list=tool_list or self._fallback_empty_tool_list(),
+ tool_aliases=tool_aliases or self._fallback_empty_tool_list(),
+ max_parallel_tools=MAX_PARALLEL_TOOL_CALLS,
)
def _react_fallback_system_prompt(self, tool_table: str) -> str:
- return self._text(
- zh=(
- "你是 DeepTutor 的 ReAct 工具代理。你必须只输出一个 JSON 对象,不要输出其他文本。\n\n"
- "JSON 格式:\n"
- '{\n "action": "<tool_name_or_done>",\n "action_input": { ... }\n}\n\n'
- "可选动作如下:\n"
- f"{tool_table}\n\n"
- "先基于用户问题和可用工具列表判断是否真的需要工具;若需要,请选择最能补足关键信息缺口的那个工具。"
- "如果不需要工具,请输出 action=done。"
- ),
- en=(
- "You are DeepTutor's ReAct tool agent. Output exactly one JSON object and nothing else.\n\n"
- "JSON format:\n"
- '{\n "action": "<tool_name_or_done>",\n "action_input": { ... }\n}\n\n'
- "Available actions:\n"
- f"{tool_table}\n\n"
- "Decide from the user request and the full enabled tool list whether tool use is truly needed; if it is, choose the single tool that best closes the most important information gap. "
- "If no tool is needed, set action=done."
- ),
- )
+ return self._t("react_fallback.system", tool_table=tool_table)
def _thinking_system_prompt(self, enabled_tools: list[str], context: UnifiedContext) -> str:
kb_name = context.knowledge_bases[0] if context.knowledge_bases else ""
@@ -1198,26 +1116,12 @@ class AgenticChatPipeline:
language=self.language,
kb_name=kb_name,
)
- return self._text(
- zh=(
- "你是 DeepTutor 的 thinking 阶段。请先分析用户问题,判断目标、已知条件、缺失信息,"
- "并思考是否需要后续工具调用。这里输出的是 tutor 的内部思路,不是最终回复。"
- "\n\n要求:\n"
- "1. 流式、简洁、自然地输出思考过程。\n"
- "2. 可以明确指出你预计会使用哪些工具,但此阶段不要真正调用工具。\n"
- "3. 如果用户开启了工具,请结合可用工具来规划。\n\n"
- f"当前启用工具:\n{tool_list or '- 无'}"
- ),
- en=(
- "You are DeepTutor's thinking stage. Analyze the user's request, identify goals, constraints, "
- "missing information, and whether later tool use is needed. This is the tutor's internal reasoning, "
- "not the final answer.\n\n"
- "Requirements:\n"
- "1. Stream concise, natural reasoning.\n"
- "2. You may mention which tools seem useful, but do not call tools in this stage.\n"
- "3. If tools are enabled, factor them into your plan.\n\n"
- f"Enabled tools:\n{tool_list or '- none'}"
- ),
+ has_kb = "rag" in enabled_tools and bool(context.knowledge_bases)
+ kb_hint = self._t("thinking.kb_hint") if has_kb else ""
+ return self._t(
+ "thinking.system",
+ tool_list=tool_list or self._fallback_empty_tool_list(),
+ kb_hint=kb_hint,
)
def _observing_system_prompt(self, enabled_tools: list[str]) -> str:
@@ -1226,25 +1130,12 @@ class AgenticChatPipeline:
format="list",
language=self.language,
)
- return self._text(
- zh=(
- "你是 DeepTutor 的 observing 阶段。请基于 thinking 和 acting 阶段的输出,"
- "整理一份内部观察总结,供最终回答阶段使用。不要直接回答学生。"
- "\n\n优先总结:\n"
- "1. 已确认的事实与结论\n"
- "2. 工具结果带来的关键证据\n"
- "3. 仍需在最终回答中解释清楚的点\n\n"
- f"本轮可用工具背景:\n{tool_list or '- 无'}"
- ),
- en=(
- "You are DeepTutor's observing stage. Based on the outputs from the thinking and acting stages, "
- "prepare an internal synthesis for the final answer stage. Do not answer the student directly.\n\n"
- "Prioritize:\n"
- "1. confirmed facts and conclusions\n"
- "2. key evidence from tool outputs\n"
- "3. what the final answer must explain clearly\n\n"
- f"Tool context for this turn:\n{tool_list or '- none'}"
- ),
+ has_rag = "rag" in enabled_tools
+ rag_hint = self._t("observing.rag_hint") if has_rag else ""
+ return self._t(
+ "observing.system",
+ tool_list=tool_list or self._fallback_empty_tool_list(),
+ rag_hint=rag_hint,
)
def _responding_system_prompt(self, enabled_tools: list[str]) -> str:
@@ -1253,49 +1144,28 @@ class AgenticChatPipeline:
format="list",
language=self.language,
)
- return self._text(
- zh=(
- "你是 DeepTutor 的最终回答阶段。请根据 observation 和工具结果,"
- "给用户一个清晰、直接、结构良好的正式答复。"
- "\n\n要求:\n"
- "1. 只输出面向用户的正式回答。\n"
- "2. 不要暴露内部链路、思考过程或工具编排。\n"
- "3. 若工具结果提供了证据或限制,请自然融入答案。\n\n"
- f"本轮工具背景:\n{tool_list or '- 无'}"
- ),
- en=(
- "You are DeepTutor's final response stage. Use the observation and tool evidence to provide a clear, "
- "direct, well-structured answer to the user.\n\n"
- "Requirements:\n"
- "1. Output only the final user-facing answer.\n"
- "2. Do not reveal the internal chain, reasoning, or tool orchestration.\n"
- "3. Naturally integrate evidence or limits surfaced by the tools.\n\n"
- f"Tool context for this turn:\n{tool_list or '- none'}"
- ),
+ has_rag = "rag" in enabled_tools
+ rag_hint = self._t("responding.rag_hint") if has_rag else ""
+ return self._t(
+ "responding.system",
+ tool_list=tool_list or self._fallback_empty_tool_list(),
+ rag_hint=rag_hint,
)
def _acting_user_prompt(self, context: UnifiedContext, thinking_text: str) -> str:
- return self._text(
- zh=(
- f"用户问题:\n{context.user_message}\n\n"
- f"{self._labeled_block('Thinking', thinking_text)}\n\n"
- "请先基于问题与全部可用工具,判断有哪些信息缺口需要工具补足。"
- f"如果需要,请尽量在同一轮并行调用多个互补工具,但总数不要超过 {MAX_PARALLEL_TOOL_CALLS} 个。"
- ),
- en=(
- f"User request:\n{context.user_message}\n\n"
- f"{self._labeled_block('Thinking', thinking_text)}\n\n"
- "First reason about which information gaps require tools, using the full enabled tool list. "
- f"If tool use is needed, prefer calling multiple complementary tools in the same turn, up to {MAX_PARALLEL_TOOL_CALLS} total."
- ),
+ return self._t(
+ "acting.user",
+ user_message=context.user_message,
+ thinking=thinking_text.strip() if thinking_text.strip() else "(empty)",
+ max_parallel_tools=MAX_PARALLEL_TOOL_CALLS,
)
+ def _fallback_empty_tool_list(self) -> str:
+ return "- 无" if self.language == "zh" else "- none"
+
def _format_tool_traces(self, tool_traces: list[ToolTrace]) -> str:
if not tool_traces:
- return self._text(
- zh="本轮没有实际工具调用。",
- en="No tools were actually called in this turn.",
- )
+ return self._t("empty.no_tool_traces")
blocks: list[str] = []
for idx, trace in enumerate(tool_traces, start=1):
@@ -1313,10 +1183,7 @@ class AgenticChatPipeline:
def _format_answer_now_events(self, events: Any) -> str:
if not isinstance(events, list) or not events:
- return self._text(
- zh="没有可用的中间执行记录。",
- en="No intermediate execution trace was provided.",
- )
+ return self._t("empty.no_intermediate_trace")
lines: list[str] = []
for index, event in enumerate(events, start=1):
@@ -1339,10 +1206,7 @@ class AgenticChatPipeline:
lines.append(line)
if not lines:
- return self._text(
- zh="没有可用的中间执行记录。",
- en="No intermediate execution trace was provided.",
- )
+ return self._t("empty.no_intermediate_trace")
return "\n".join(lines)
@staticmethod
@@ -1366,14 +1230,7 @@ class AgenticChatPipeline:
return cleaned[: limit - 3].rstrip() + "..."
def _images_stripped_notice(self) -> str:
- return self._text(
- zh=(
- f"当前模型 `{self.model}` 不支持图像输入,thinking 阶段已忽略本轮图片附件。"
- ),
- en=(
- f"The current model `{self.model}` does not support image input, so image attachments were ignored in the thinking stage."
- ),
- )
+ return self._t("notices.images_stripped", model=self.model or "")
@staticmethod
def _labeled_block(label: str, content: str) -> str:
@@ -1381,3 +1238,25 @@ class AgenticChatPipeline:
def _text(self, *, zh: str, en: str) -> str:
return zh if self.language == "zh" else en
+
+ def _t(self, key: str, default: str = "", **kwargs: Any) -> str:
+ """Look up a YAML-loaded prompt by dotted key (e.g. ``thinking.system``).
+
+ - Returns ``default`` if the key is missing or value is not a string.
+ - When ``kwargs`` are passed, the string is rendered via ``str.format``;
+ missing placeholders fall back to the unrendered template instead of
+ crashing the pipeline.
+ """
+ value: Any = self._prompts
+ for part in key.split("."):
+ if not isinstance(value, dict) or part not in value:
+ return default
+ value = value[part]
+ if not isinstance(value, str):
+ return default
+ if kwargs:
+ try:
+ return value.format(**kwargs)
+ except (KeyError, IndexError, ValueError):
+ return value
+ return value
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
new file mode 100644
index 000000000..ef7cc6e14
--- /dev/null
+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
@@ -0,0 +1,178 @@
+# AgenticChatPipeline prompts (English)
+# These prompts are consumed by deeptutor.agents.chat.agentic_pipeline.AgenticChatPipeline,
+# which powers the chat capability's 4-stage pipeline: thinking → acting → observing → responding.
+# Independent from chat_agent.yaml in this folder (used by the legacy single-turn ChatAgent).
+
+# ---------------------------------------------------------------------------
+# Stage labels (used in trace metadata, surfaced in UI)
+# ---------------------------------------------------------------------------
+labels:
+ reasoning: "Reasoning"
+ observation: "Observation"
+ final_response: "Final response"
+ tool_call: "Tool call"
+ retrieve: "Retrieve"
+
+# ---------------------------------------------------------------------------
+# Thinking stage
+# ---------------------------------------------------------------------------
+thinking:
+ system: |-
+ You are DeepTutor's internal thinking module (NOT user-facing). Your output is a brief internal analysis memo consumed by the downstream acting / responding stages. It will never be shown to the user directly.
+
+ Output format (use natural paragraphs, no headings needed):
+ - User goal: summarize what the user actually wants in 1-2 sentences.
+ - Known vs. missing: what information is already available in the conversation, and what is still missing.
+ - Tool plan: which tools could fill the gaps, with brief rationale. Write "No tools needed" if information is sufficient.
+ - Answer key points: 2-4 key points the final answer should cover.
+
+ Critical constraints:
+ - Output ONLY the internal analysis memo. Do NOT produce a user-facing answer, conclusion, or worked solution.
+ - You may mention which tools seem useful, but do not call tools in this stage.
+ - Keep it concise — no more than 200 words.
+ {kb_hint}
+ Enabled tools:
+ {tool_list}
+ # Injected at {kb_hint} when RAG is enabled and a knowledge base is selected
+ kb_hint: |-
+ - A knowledge base is active (RAG). The question may benefit from retrieval. Assess whether KB retrieval would help and plan accordingly — avoid premature conclusions from memory alone.
+ user: |-
+ [User request]
+ {user_message}
+
+ Produce the internal analysis memo (do NOT answer the user or draw conclusions).
+
+# ---------------------------------------------------------------------------
+# Acting stage
+# ---------------------------------------------------------------------------
+acting:
+ system: |-
+ You are DeepTutor's tool-using agent. Based on the user request and prior thinking, autonomously choose and call only the enabled tools that are truly helpful.
+
+ Rules:
+ 1. Review the full enabled tool list before deciding; do not fixate on a single tool too early.
+ 2. For complex questions that need definitions, grounding, outside evidence, papers, calculation, or deeper reasoning, prefer calling multiple complementary tools in parallel so each one covers a distinct information need.
+ 3. Call tools only when they add value, but when they materially improve answer quality you should use them fully.
+ 4. Use concrete, executable arguments grounded in the user's request, and adapt the wording when different tools need different query styles.
+ 5. If enough evidence already exists, you may skip tool use.
+ 6. Do not produce the final student-facing answer here; this stage is only for tool use.
+ 7. At most {max_parallel_tools} tools may run in parallel in one turn; if several complementary tools are relevant, prefer issuing them together in the same turn.
+
+ Enabled tools:
+ {tool_list}
+
+ Tool usage notes:
+ {tool_aliases}
+ user: |-
+ User request:
+ {user_message}
+
+ [Thinking]
+ {thinking}
+
+ First reason about which information gaps require tools, using the full enabled tool list. If tool use is needed, prefer calling multiple complementary tools in the same turn, up to {max_parallel_tools} total.
+
+# ---------------------------------------------------------------------------
+# Observing stage
+# ---------------------------------------------------------------------------
+observing:
+ system: |-
+ You are DeepTutor's observing stage. Based on the outputs from the thinking and acting stages, prepare an internal synthesis for the final answer stage. Do not answer the student directly.
+
+ Prioritize:
+ 1. confirmed facts and conclusions
+ 2. key evidence from tool outputs
+ 3. what the final answer must explain clearly
+ {rag_hint}
+ Tool context for this turn:
+ {tool_list}
+ # Injected at {rag_hint} when RAG is enabled
+ rag_hint: |-
+ If RAG (knowledge base retrieval) was called, assess whether the question is best answered from the retrieved content, from memory / general knowledge, or a mix of both — include this judgment in your synthesis. When tool evidence conflicts with the initial thinking, prefer the evidence.
+ user_intro: |-
+ Summarize what was learned from the reasoning and tool execution for the tutor's internal observation note. Focus on confirmed facts, remaining uncertainty, and what the final answer should emphasize. Do not address the student directly.
+
+# ---------------------------------------------------------------------------
+# Responding stage (final user-facing answer)
+# ---------------------------------------------------------------------------
+responding:
+ system: |-
+ You are DeepTutor's final response stage. Use the observation and tool evidence to provide a clear, direct, well-structured answer to the user.
+
+ Requirements:
+ 1. Output only the final user-facing answer.
+ 2. Do not reveal the internal chain, reasoning, or tool orchestration.
+ 3. Naturally integrate evidence or limits surfaced by the tools.
+ {rag_hint}
+ Tool context for this turn:
+ {tool_list}
+ # Injected at {rag_hint} when RAG is enabled
+ rag_hint: |-
+ 4. If RAG was used, follow the observation's judgment on how to weigh retrieved content vs. general knowledge. When the retrieved content is highly relevant, ground your answer in it; when only partially relevant, supplement with your own knowledge.
+ user: |-
+ User request:
+ {user_message}
+
+ [Observation]
+ {observation}
+
+ [Tool Trace]
+ {tool_trace}
+
+ Use this material to produce the final answer for the user. Do not mention the internal pipeline, thinking, or observing stages.
+
+# ---------------------------------------------------------------------------
+# ReAct fallback (when native tool calling is unavailable)
+# ---------------------------------------------------------------------------
+react_fallback:
+ system: |-
+ You are DeepTutor's ReAct tool agent. Output exactly one JSON object and nothing else.
+
+ JSON format:
+ {{
+ "action": "<tool_name_or_done>",
+ "action_input": {{ ... }}
+ }}
+
+ Available actions:
+ {tool_table}
+
+ Decide from the user request and the full enabled tool list whether tool use is truly needed; if it is, choose the single tool that best closes the most important information gap. If no tool is needed, set action=done.
+ done_when_to_use: "Use when the available information is sufficient and no more tools are needed."
+ done_input_format: "Empty string."
+
+# ---------------------------------------------------------------------------
+# Answer-now stage (user explicitly requested "answer now", skip further planning)
+# ---------------------------------------------------------------------------
+answer_now:
+ user: |-
+ Original user request:
+ {original_user_message}
+
+ [Current Draft]
+ {partial_response}
+
+ [Execution Trace]
+ {trace_summary}
+
+ Using only the material already gathered so far, produce the final user-facing answer now. Do not continue planning or call tools, and do not mention internal stages. If something is still uncertain, be explicit about the uncertainty while still giving the most useful answer you can.
+
+# ---------------------------------------------------------------------------
+# Progress notices and short copy
+# ---------------------------------------------------------------------------
+notices:
+ no_tools_enabled: "No tools are enabled for this turn, so tool execution was skipped."
+ react_fallback_switch: "The current model does not support native tool calling, so ReAct text orchestration is used."
+ no_tool_call_needed: "No tool call was needed for this turn."
+ too_many_tool_calls: "The model requested {requested} tools. At most {limit} can run in parallel in one turn, so the list was truncated."
+ tool_unknown_error: "An unknown error occurred while executing {tool}."
+ start_retrieval: "Starting retrieval"
+ empty_tool_result: "The tool completed without returning text output."
+ images_stripped: "The current model `{model}` does not support image input, so image attachments were ignored in the thinking stage."
+
+# ---------------------------------------------------------------------------
+# Empty-state copy
+# ---------------------------------------------------------------------------
+empty:
+ no_tool_traces: "No tools were actually called in this turn."
+ no_intermediate_trace: "No intermediate execution trace was provided."
diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
new file mode 100644
index 000000000..47f01f53e
--- /dev/null
+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
@@ -0,0 +1,178 @@
+# AgenticChatPipeline 提示词(中文)
+# 这些提示词供 deeptutor.agents.chat.agentic_pipeline.AgenticChatPipeline 使用,
+# 对应 chat capability 的四阶段 pipeline:thinking → acting → observing → responding。
+# 与同目录下 chat_agent.yaml(旧的 REST 单轮 ChatAgent 用)不冲突。
+
+# ---------------------------------------------------------------------------
+# 各阶段标签(用于 trace metadata,前端展示)
+# ---------------------------------------------------------------------------
+labels:
+ reasoning: "Reasoning"
+ observation: "Observation"
+ final_response: "Final response"
+ tool_call: "Tool call"
+ retrieve: "Retrieve"
+
+# ---------------------------------------------------------------------------
+# Thinking 阶段
+# ---------------------------------------------------------------------------
+thinking:
+ system: |-
+ 你是 DeepTutor 内部的 thinking 模块(不面向用户)。你的产出是一份简短的内部分析备忘,供后续 acting / responding 阶段消费,绝不会直接展示给用户。
+
+ 产出格式(用自然段落,不需要标题):
+ - 用户目标:用一两句话概括用户真正想要什么。
+ - 已知 vs. 缺失:当前对话和上下文中已经有什么信息,还缺什么。
+ - 工具规划:哪些工具可能补足缺失信息,简要说明理由。如果信息已足够,写"无需工具"。
+ - 回答要点:最终回答应覆盖的关键点(列 2-4 条)。
+
+ 关键约束:
+ - 你只输出内部分析备忘,不要给出面向用户的回答、结论或解题过程。
+ - 可以提及预计使用哪些工具,但不要真正调用工具。
+ - 保持简洁,不超过 200 字。
+ {kb_hint}
+ 当前启用工具:
+ {tool_list}
+ # 当 RAG 工具启用且有知识库时,会插入到 system 的 {kb_hint} 占位处
+ kb_hint: |-
+ - 用户已启用知识库检索(RAG),其问题可能需要从知识库中获取答案。请评估问题是否适合通过检索来回答,并据此规划检索策略,避免过早从记忆中得出结论。
+ user: |-
+ [用户问题]
+ {user_message}
+
+ 请输出内部分析备忘(不要回答用户,不要给出结论)。
+
+# ---------------------------------------------------------------------------
+# Acting 阶段
+# ---------------------------------------------------------------------------
+acting:
+ system: |-
+ 你是 DeepTutor 的工具调用代理。你的任务是根据用户问题和前序 thinking,从当前已启用的工具中自主选择必要工具并调用。
+
+ 规则:
+ 1. 先完整审视所有已启用工具,再决定最有帮助的工具组合;不要只盯住单个工具。
+ 2. 对于需要定义、事实核验、外部资料、论文、计算、推理等不同信息面的复杂问题,优先并行调用多个互补工具来覆盖这些信息面。
+ 3. 只调用真正有帮助的工具,但只要工具能显著提升答案质量,就应充分调用。
+ 4. 参数要具体、可执行,优先使用用户原问题中的关键信息,必要时针对不同工具改写成最适合它的查询。
+ 5. 如果信息已经足够,可以不调用工具。
+ 6. 不要输出最终回答给学生;这里只负责工具选择与调用。
+ 7. 单轮最多并行调用 {max_parallel_tools} 个工具;如果有多个互补工具都相关,优先在同一轮一起调用。
+
+ 当前可用工具:
+ {tool_list}
+
+ 工具使用提示:
+ {tool_aliases}
+ user: |-
+ 用户问题:
+ {user_message}
+
+ [Thinking]
+ {thinking}
+
+ 请先基于问题与全部可用工具,判断有哪些信息缺口需要工具补足。如果需要,请尽量在同一轮并行调用多个互补工具,但总数不要超过 {max_parallel_tools} 个。
+
+# ---------------------------------------------------------------------------
+# Observing 阶段
+# ---------------------------------------------------------------------------
+observing:
+ system: |-
+ 你是 DeepTutor 的 observing 阶段。请基于 thinking 和 acting 阶段的输出,整理一份内部观察总结,供最终回答阶段使用。不要直接回答学生。
+
+ 优先总结:
+ 1. 已确认的事实与结论
+ 2. 工具结果带来的关键证据
+ 3. 仍需在最终回答中解释清楚的点
+ {rag_hint}
+ 本轮可用工具背景:
+ {tool_list}
+ # 当 RAG 工具被启用时,插入到 system 的 {rag_hint} 占位处
+ rag_hint: |-
+ 若本轮调用了知识库检索(RAG),请评估用户问题更适合基于检索到的知识库内容回答、基于记忆与通识回答、还是两者结合,并将判断写入总结。当工具返回的证据与初始 thinking 的推断不一致时,以实际证据为准。
+ user_intro: |-
+ 请整理本轮推理与工具执行得到的关键信息,输出给 tutor 自己看的观察总结。聚焦:已确认事实、仍不确定的点、最终回答应强调什么。不要直接写给学生。
+
+# ---------------------------------------------------------------------------
+# Responding 阶段(最终面向用户)
+# ---------------------------------------------------------------------------
+responding:
+ system: |-
+ 你是 DeepTutor 的最终回答阶段。请根据 observation 和工具结果,给用户一个清晰、直接、结构良好的正式答复。
+
+ 要求:
+ 1. 只输出面向用户的正式回答。
+ 2. 不要暴露内部链路、思考过程或工具编排。
+ 3. 若工具结果提供了证据或限制,请自然融入答案。
+ {rag_hint}
+ 本轮工具背景:
+ {tool_list}
+ # 当 RAG 工具被启用时,插入到 system 的 {rag_hint} 占位处
+ rag_hint: |-
+ 4. 若使用了知识库检索,请根据 observation 的判断,合理权衡检索内容与通识。当检索内容与问题高度相关时,以其为核心依据;部分相关时,可结合自身知识补充。
+ user: |-
+ 用户问题:
+ {user_message}
+
+ [Observation]
+ {observation}
+
+ [Tool Trace]
+ {tool_trace}
+
+ 请基于以上内容,直接给出正式回答。不要暴露内部 pipeline、thinking、observing 等字样。
+
+# ---------------------------------------------------------------------------
+# ReAct fallback(不支持原生 tool-calling 时的回退)
+# ---------------------------------------------------------------------------
+react_fallback:
+ system: |-
+ 你是 DeepTutor 的 ReAct 工具代理。你必须只输出一个 JSON 对象,不要输出其他文本。
+
+ JSON 格式:
+ {{
+ "action": "<tool_name_or_done>",
+ "action_input": {{ ... }}
+ }}
+
+ 可选动作如下:
+ {tool_table}
+
+ 先基于用户问题和可用工具列表判断是否真的需要工具;若需要,请选择最能补足关键信息缺口的那个工具。如果不需要工具,请输出 action=done。
+ done_when_to_use: "当已有信息足够,且不需要继续调用工具时使用。"
+ done_input_format: "空字符串。"
+
+# ---------------------------------------------------------------------------
+# Answer-now 阶段(用户主动请求"立即回答",跳过后续规划)
+# ---------------------------------------------------------------------------
+answer_now:
+ user: |-
+ 用户原始问题:
+ {original_user_message}
+
+ [Current Draft]
+ {partial_response}
+
+ [Execution Trace]
+ {trace_summary}
+
+ 请基于当前已经完成的内容,立刻直接生成给用户的最终答复。不要继续规划或调用工具,不要提到内部阶段。如果信息仍有缺口,请诚实说明不确定之处,但仍尽可能先给出当前最有用的回答。
+
+# ---------------------------------------------------------------------------
+# 进度提示与短文案
+# ---------------------------------------------------------------------------
+notices:
+ no_tools_enabled: "当前没有启用任何工具,本轮跳过工具调用。"
+ react_fallback_switch: "当前模型不支持原生工具调用,已切换到 ReAct 文本编排。"
+ no_tool_call_needed: "本轮不需要调用工具。"
+ too_many_tool_calls: "模型请求了 {requested} 个工具,本轮最多并行执行 {limit} 个,已截断。"
+ tool_unknown_error: "执行工具 {tool} 时发生未知错误。"
+ start_retrieval: "开始检索"
+ empty_tool_result: "工具执行完成,但没有返回文本内容。"
+ images_stripped: "当前模型 `{model}` 不支持图像输入,thinking 阶段已忽略本轮图片附件。"
+
+# ---------------------------------------------------------------------------
+# 空状态文案
+# ---------------------------------------------------------------------------
+empty:
+ no_tool_traces: "本轮没有实际工具调用。"
+ no_intermediate_trace: "没有可用的中间执行记录。"
diff --git a/deeptutor/agents/research/agents/decompose_agent.py b/deeptutor/agents/research/agents/decompose_agent.py
index b3fa50a6c..0f9c14b8d 100644
--- a/deeptutor/agents/research/agents/decompose_agent.py
+++ b/deeptutor/agents/research/agents/decompose_agent.py
@@ -44,7 +44,7 @@ class DecomposeAgent(BaseAgent):
api_key: str | None = None,
base_url: str | None = None,
api_version: str | None = None,
- kb_name: str = "ai_textbook",
+ kb_name: str | None = None,
):
language = config.get("system", {}).get("language", "zh")
super().__init__(
@@ -56,11 +56,17 @@ class DecomposeAgent(BaseAgent):
language=language,
config=config,
)
- rag_cfg = config.get("rag", {})
- self.kb_name = rag_cfg.get("kb_name", kb_name or "ai_textbook")
+ rag_cfg = config.get("rag", {}) or {}
+ self.kb_name = rag_cfg.get("kb_name") or kb_name or None
researching_cfg = config.get("researching", {})
self.enable_rag = researching_cfg.get("enable_rag", True)
+ # Defensive: never attempt RAG without a real KB name. The
+ # capability/runtime config layer is responsible for stripping
+ # ``kb`` from sources when no KB is attached, but this guard keeps
+ # the agent safe even when called directly.
+ if not self.kb_name:
+ self.enable_rag = False
self.conversation_history: list[dict[str, Any]] = config.get("conversation_history", [])
@@ -173,6 +179,9 @@ class DecomposeAgent(BaseAgent):
source_query = (topic or "").strip()
if not source_query:
return "", ""
+ if not self.kb_name:
+ print(" ⚠️ No knowledge base configured; skipping RAG retrieval.")
+ return "", source_query
try:
result = await rag_search(query=source_query, kb_name=self.kb_name)
diff --git a/deeptutor/agents/research/request_config.py b/deeptutor/agents/research/request_config.py
index 11dea1037..6ef66994b 100644
--- a/deeptutor/agents/research/request_config.py
+++ b/deeptutor/agents/research/request_config.py
@@ -169,7 +169,7 @@ def build_research_runtime_config(
if isinstance(research_root.get("reporting"), dict)
else {}
)
- rag_root = research_root.get("rag", {}) if isinstance(research_root.get("rag"), dict) else {}
+ rag_root: dict = {}
policy = build_research_execution_policy(
request_config=request_config,
enabled_tools=enabled_tools,
diff --git a/deeptutor/agents/research/research_pipeline.py b/deeptutor/agents/research/research_pipeline.py
index a74244ae5..dea34188b 100644
--- a/deeptutor/agents/research/research_pipeline.py
+++ b/deeptutor/agents/research/research_pipeline.py
@@ -293,8 +293,37 @@ class ResearchPipeline:
try:
if tool_type in ("rag_hybrid", "rag_naive", "rag"):
- rag_cfg = self.config.get("rag", {})
- kb_name = rag_cfg.get("kb_name", "DE-all")
+ rag_cfg = self.config.get("rag", {}) or {}
+ kb_name = rag_cfg.get("kb_name")
+ if not kb_name:
+ skipped = json.dumps(
+ {
+ "status": "skipped",
+ "reason": "no_kb_selected",
+ "message": (
+ "RAG retrieval was requested but no "
+ "knowledge base is configured for this "
+ "research run."
+ ),
+ "tool": "rag",
+ "query": query,
+ },
+ ensure_ascii=False,
+ )
+ await self._emit_trace_event(
+ {
+ "event": "tool_result",
+ "phase": "researching",
+ "call_id": call_id,
+ "label": "Use rag",
+ "call_kind": "tool_execution",
+ "tool_name": "rag",
+ "result": skipped,
+ "state": "skipped",
+ "query": query,
+ }
+ )
+ return skipped
result = await self._call_tool_with_retry(
self._tool_registry.execute,
"rag",
@@ -338,17 +367,29 @@ class ResearchPipeline:
tool_name="run_code",
)
else:
- rag_cfg = self.config.get("rag", {})
- kb_name = rag_cfg.get("kb_name", "DE-all")
- result = await self._call_tool_with_retry(
- self._tool_registry.execute,
- "rag",
- query=query,
- kb_name=kb_name,
- max_retries=max_retries,
- timeout=default_timeout,
- tool_name="rag",
+ unknown = json.dumps(
+ {
+ "status": "failed",
+ "reason": "unknown_tool",
+ "tool": tool_type,
+ "query": query,
+ },
+ ensure_ascii=False,
+ )
+ await self._emit_trace_event(
+ {
+ "event": "tool_result",
+ "phase": "researching",
+ "call_id": call_id,
+ "label": f"Use {tool_type or 'tool'}",
+ "call_kind": "tool_execution",
+ "tool_name": tool_type or "tool",
+ "result": unknown,
+ "state": "error",
+ "query": query,
+ }
)
+ return unknown
except Exception as e:
failure = json.dumps(
{"status": "failed", "error": str(e), "tool": tool_type, "query": query},
diff --git a/deeptutor/agents/solve/tool_runtime.py b/deeptutor/agents/solve/tool_runtime.py
index 4dd233db3..29c1b8497 100644
--- a/deeptutor/agents/solve/tool_runtime.py
+++ b/deeptutor/agents/solve/tool_runtime.py
@@ -122,12 +122,29 @@ class SolveToolRuntime:
temperature: float | None = None,
event_sink: Any | None = None,
) -> ToolResult:
+ from deeptutor.core.tool_protocol import ToolResult as _ToolResult
+
tool = self._core_registry.get(action)
if tool is None:
raise KeyError(f"Unknown tool action: {action}")
if tool.name not in self._tool_names:
raise PermissionError(f"Tool action '{action}' is not enabled for solve.")
+ # Defensive guard: rag without a knowledge base must never reach the
+ # underlying RAG service. Returning a structured ToolResult keeps the
+ # ReAct loop alive (the LLM sees a clear observation and can replan).
+ if tool.name == "rag" and not kb_name:
+ return _ToolResult(
+ content=(
+ "RAG retrieval was requested, but no knowledge base is "
+ "configured for this turn. Continue without retrieved "
+ "knowledge or ask the user to select a knowledge base."
+ ),
+ sources=[],
+ metadata={"skipped": True, "reason": "no_kb_selected"},
+ success=False,
+ )
+
kwargs = self._build_action_input_kwargs(tool.name, action_input)
kwargs = self._apply_runtime_context(
tool_name=tool.name,
diff --git a/deeptutor/api/routers/_tutorbot_channel_schema.py b/deeptutor/api/routers/_tutorbot_channel_schema.py
new file mode 100644
index 000000000..e4b712080
--- /dev/null
+++ b/deeptutor/api/routers/_tutorbot_channel_schema.py
@@ -0,0 +1,170 @@
+"""Channel-schema introspection — bridges Pydantic channel configs to the Web UI.
+
+Used by ``GET /api/v1/tutorbot/channels/schema`` so the front-end can render
+generic forms for ANY channel (built-in or plugin) without hard-coding fields.
+
+Why live here vs inside ``deeptutor.tutorbot.channels``?
+ * This is an API-shaping concern (JSON Schema flattening, secret-field
+ detection) — keeping it next to the route avoids polluting the runtime
+ channel package with HTTP-specific helpers.
+"""
+
+from __future__ import annotations
+
+import inspect
+from typing import Any
+
+from pydantic import BaseModel
+
+from deeptutor.services.tutorbot.manager import _is_secret_field
+
+
+def resolve_config_model(channel_cls: type) -> type[BaseModel] | None:
+ """Find the Pydantic config model paired with ``channel_cls``.
+
+ Convention every built-in channel follows: ``XxxChannel`` lives in the
+ same module as ``XxxConfig`` (e.g. ``TelegramChannel`` ↔ ``TelegramConfig``).
+ Falls back to "any ``*Config`` BaseModel in the module".
+ """
+ module = inspect.getmodule(channel_cls)
+ if module is None:
+ return None
+
+ expected = channel_cls.__name__.replace("Channel", "") + "Config"
+ candidate = getattr(module, expected, None)
+ if isinstance(candidate, type) and issubclass(candidate, BaseModel):
+ return candidate
+
+ for _, obj in inspect.getmembers(module):
+ if (
+ isinstance(obj, type)
+ and obj is not BaseModel
+ and issubclass(obj, BaseModel)
+ and obj.__name__.endswith("Config")
+ ):
+ return obj
+ return None
+
+
+def inline_refs(schema: dict[str, Any]) -> dict[str, Any]:
+ """Flatten Pydantic's ``$defs`` / ``$ref`` so the front-end doesn't need a resolver.
+
+ Nested model fields (e.g. ``slack.dm: SlackDMConfig``) become inline
+ ``type: object`` subtrees with their own ``properties``.
+ """
+ defs: dict[str, Any] = dict(schema.get("$defs", {}))
+
+ def _walk(node: Any) -> Any:
+ if isinstance(node, dict):
+ ref = node.get("$ref")
+ if isinstance(ref, str) and ref.startswith("#/$defs/"):
+ ref_name = ref.rsplit("/", 1)[-1]
+ resolved = defs.get(ref_name, {})
+ merged = {**resolved}
+ # Allow per-field overrides (description, default) from the ref site.
+ for k, v in node.items():
+ if k != "$ref":
+ merged[k] = v
+ return _walk(merged)
+ return {k: _walk(v) for k, v in node.items()}
+ if isinstance(node, list):
+ return [_walk(item) for item in node]
+ return node
+
+ out = _walk(schema)
+ if isinstance(out, dict):
+ out.pop("$defs", None)
+ return out
+
+
+def _schema_accepts_string(prop_schema: dict[str, Any]) -> bool:
+ """True iff the JSON-Schema fragment can hold a string value.
+
+ Used to filter out booleans/integers/arrays whose name happens to contain
+ a secret-looking substring (e.g. ``user_token_read_only: bool``).
+ """
+ t = prop_schema.get("type")
+ if t == "string":
+ return True
+ if isinstance(t, list) and "string" in t:
+ return True
+ for variant in prop_schema.get("anyOf", []):
+ if isinstance(variant, dict) and variant.get("type") == "string":
+ return True
+ return False
+
+
+def collect_secret_fields(schema: dict[str, Any], prefix: str = "") -> list[str]:
+ """Return dot-paths for every string-typed property whose name hints at a secret.
+
+ e.g. ``["token"]`` for telegram, ``["imap_password", "smtp_password"]``
+ for email, ``["bot_token", "app_token"]`` for slack. A field like
+ ``user_token_read_only: bool`` is intentionally skipped.
+ """
+ paths: list[str] = []
+ properties = schema.get("properties") if isinstance(schema, dict) else None
+ if not isinstance(properties, dict):
+ return paths
+
+ for prop_name, prop_schema in properties.items():
+ if not isinstance(prop_schema, dict):
+ continue
+ full = f"{prefix}{prop_name}" if not prefix else f"{prefix}.{prop_name}"
+ if _is_secret_field(prop_name) and _schema_accepts_string(prop_schema):
+ paths.append(full)
+ if prop_schema.get("type") == "object":
+ paths.extend(collect_secret_fields(prop_schema, prefix=full))
+ return paths
+
+
+def channel_schema_payload(channel_cls: type) -> dict[str, Any] | None:
+ """Build the per-channel schema payload, or ``None`` if no config model found."""
+ model = resolve_config_model(channel_cls)
+ if model is None:
+ return None
+
+ # by_alias=False → property names match Python field names (snake_case),
+ # which is exactly the shape we persist in ``config.yaml`` and what every
+ # channel's ``__init__`` expects when ``model_validate(dict)`` is called.
+ # The pydantic Base config has populate_by_name=True so the runtime still
+ # accepts both forms; we standardise on snake_case for the wire schema.
+ raw = model.model_json_schema(by_alias=False)
+ flat = inline_refs(raw)
+ secret_fields = collect_secret_fields(flat)
+
+ try:
+ default_config = model().model_dump(mode="json", by_alias=False)
+ except Exception:
+ default_config = {}
+
+ return {
+ "name": getattr(channel_cls, "name", channel_cls.__name__),
+ "display_name": getattr(channel_cls, "display_name", channel_cls.__name__),
+ "default_config": default_config,
+ "secret_fields": secret_fields,
+ "json_schema": flat,
+ }
+
+
+def all_channel_schemas() -> dict[str, dict[str, Any]]:
+ """Build the schema dict for every discovered channel (built-in + plugins)."""
+ from deeptutor.tutorbot.channels.registry import discover_all
+
+ out: dict[str, dict[str, Any]] = {}
+ for name, cls in discover_all().items():
+ payload = channel_schema_payload(cls)
+ if payload is not None:
+ out[name] = payload
+ return out
+
+
+def global_channels_schema() -> dict[str, Any]:
+ """Schema for the top-level ``ChannelsConfig`` flags (send_progress / send_tool_hints)."""
+ from deeptutor.tutorbot.config.schema import ChannelsConfig
+
+ raw = ChannelsConfig.model_json_schema(by_alias=False)
+ flat = inline_refs(raw)
+ return {
+ "json_schema": flat,
+ "secret_fields": collect_secret_fields(flat),
+ }
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index d5818726d..8266c19c8 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -32,8 +32,8 @@ from deeptutor.knowledge.add_documents import DocumentAdder
from deeptutor.knowledge.initializer import KnowledgeBaseInitializer
from deeptutor.knowledge.manager import KnowledgeBaseManager
from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
-from deeptutor.services.rag.components.routing import FileTypeRouter
-from deeptutor.services.rag.factory import DEFAULT_PROVIDER, has_pipeline, normalize_provider_name
+from deeptutor.services.rag.file_routing import FileTypeRouter
+from deeptutor.services.rag.factory import DEFAULT_PROVIDER
from deeptutor.utils.document_validator import DocumentValidator
from deeptutor.utils.error_utils import format_exception_message
@@ -171,23 +171,8 @@ def _task_log(task_id: str, message: str, level: str = "info") -> None:
def _validate_registered_provider(raw_provider: str | None) -> str:
- candidate = (raw_provider or DEFAULT_PROVIDER).strip().lower()
- if not candidate:
- candidate = DEFAULT_PROVIDER
-
- if not has_pipeline(candidate):
- from deeptutor.services.rag.service import RAGService
-
- available_providers = [item["id"] for item in RAGService.list_providers()]
- raise HTTPException(
- status_code=400,
- detail=(
- f"Unsupported RAG provider '{candidate}'. "
- f"Available providers: {available_providers}"
- ),
- )
-
- return normalize_provider_name(candidate)
+ """Always return the canonical provider; field is kept as a stub."""
+ return DEFAULT_PROVIDER
def _load_kb_entry_or_404(manager: KnowledgeBaseManager, kb_name: str) -> dict:
@@ -656,7 +641,7 @@ async def upload_files(
"Update KB config first."
),
)
- allowed_extensions = FileTypeRouter.get_extensions_for_provider(kb_provider)
+ allowed_extensions = FileTypeRouter.get_supported_extensions()
uploaded_files, uploaded_file_paths = _save_uploaded_files(
files, raw_dir, allowed_extensions=allowed_extensions
)
@@ -746,7 +731,7 @@ async def create_knowledge_base(
logger.warning(f"KB {name} not found in config, registering manually")
initializer._register_to_config()
- allowed_extensions = FileTypeRouter.get_extensions_for_provider(rag_provider)
+ 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/tutorbot.py b/deeptutor/api/routers/tutorbot.py
index cfe5ff5bc..f2fd8b33a 100644
--- a/deeptutor/api/routers/tutorbot.py
+++ b/deeptutor/api/routers/tutorbot.py
@@ -7,10 +7,15 @@ from __future__ import annotations
import json
import logging
-from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
-from pydantic import BaseModel
+from fastapi import APIRouter, HTTPException, Query, WebSocket, WebSocketDisconnect
+from pydantic import BaseModel, ValidationError
from deeptutor.services.tutorbot import get_tutorbot_manager
+from deeptutor.services.tutorbot.manager import (
+ BotConfig,
+ TutorBotInstance,
+ mask_channel_secrets,
+)
logger = logging.getLogger(__name__)
router = APIRouter()
@@ -99,6 +104,41 @@ async def recent_bots(limit: int = 3):
return get_tutorbot_manager().get_recent_active_bots(limit=limit)
[email protected]("/channels/schema")
+async def list_channel_schemas():
+ """Return JSON-Schema metadata for every available channel.
+
+ Powers the schema-driven Channels tab in the Web UI: lets it render a
+ generic form for ANY channel (built-in or plugin) without per-channel
+ front-end code. Secret-looking fields are flagged via ``secret_fields``
+ so the UI can mask them.
+
+ Shape:
+ {
+ "channels": {
+ "telegram": {
+ "name": "telegram",
+ "display_name": "Telegram",
+ "default_config": {...},
+ "secret_fields": ["token"],
+ "json_schema": {...}
+ },
+ ...
+ },
+ "global": {"json_schema": {...}, "secret_fields": []}
+ }
+ """
+ from deeptutor.api.routers._tutorbot_channel_schema import (
+ all_channel_schemas,
+ global_channels_schema,
+ )
+
+ return {
+ "channels": all_channel_schemas(),
+ "global": global_channels_schema(),
+ }
+
+
@router.post("")
async def create_and_start_bot(payload: CreateBotRequest):
mgr = get_tutorbot_manager()
@@ -112,27 +152,56 @@ async def create_and_start_bot(payload: CreateBotRequest):
instance = await mgr.start_bot(payload.bot_id, config)
except RuntimeError as e:
raise HTTPException(status_code=500, detail=str(e))
- return instance.to_dict()
+ # Response is masked — secrets are only revealed via the explicit
+ # GET /{bot_id}?include_secrets=true edit-form route.
+ return instance.to_dict(mask_secrets=True)
+
+
+def _stopped_bot_dict(
+ bot_id: str,
+ cfg: BotConfig,
+ *,
+ include_secrets: bool = False,
+) -> dict:
+ """Serialise a stopped bot — secret fields masked unless explicitly opted-in."""
+ if include_secrets:
+ channels: object = cfg.channels
+ else:
+ channels = mask_channel_secrets(cfg.channels)
+ return {
+ "bot_id": bot_id,
+ "name": cfg.name,
+ "description": cfg.description,
+ "persona": cfg.persona,
+ "channels": channels,
+ "model": cfg.model,
+ "running": False,
+ "started_at": None,
+ "last_reload_error": None,
+ }
@router.get("/{bot_id}")
-async def get_bot(bot_id: str):
+async def get_bot(
+ bot_id: str,
+ include_secrets: bool = Query(
+ False,
+ description=(
+ "Return raw channel secrets (tokens, passwords). Required by the "
+ "admin edit form; default response masks all secret-looking fields."
+ ),
+ ),
+):
mgr = get_tutorbot_manager()
instance = mgr.get_bot(bot_id)
if instance:
- return instance.to_dict()
+ return instance.to_dict(
+ include_secrets=include_secrets,
+ mask_secrets=not include_secrets,
+ )
cfg = mgr.load_bot_config(bot_id)
if cfg:
- return {
- "bot_id": bot_id,
- "name": cfg.name,
- "description": cfg.description,
- "persona": cfg.persona,
- "channels": cfg.channels,
- "model": cfg.model,
- "running": False,
- "started_at": None,
- }
+ return _stopped_bot_dict(bot_id, cfg, include_secrets=include_secrets)
raise HTTPException(status_code=404, detail="Bot not found")
@@ -152,62 +221,75 @@ async def destroy_bot(bot_id: str):
return {"bot_id": bot_id, "destroyed": True}
-def _stopped_bot_dict(bot_id: str, cfg: BotConfig) -> dict:
- return {
- "bot_id": bot_id,
- "name": cfg.name,
- "description": cfg.description,
- "persona": cfg.persona,
- "channels": cfg.channels,
- "model": cfg.model,
- "running": False,
- "started_at": None,
- }
+def _validate_channels_payload(channels: dict) -> None:
+ """Reject malformed channel configs at the API boundary (returns 422).
+
+ Without this check, the bad config would still hit disk and only blow up
+ later inside ``reload_channels`` / next ``start_bot`` — leaving a confusing
+ 500 with no guidance to the caller.
+ """
+ from deeptutor.tutorbot.config.schema import ChannelsConfig
+
+ try:
+ ChannelsConfig(**channels)
+ except ValidationError as exc:
+ raise HTTPException(
+ status_code=422,
+ detail={"message": "Invalid channels config", "errors": exc.errors()},
+ ) from None
+ except TypeError as exc:
+ raise HTTPException(
+ status_code=422,
+ detail=f"Invalid channels config: {exc}",
+ ) from None
+
+
+def _apply_payload(target: BotConfig | TutorBotInstance, payload: UpdateBotRequest) -> None:
+ """Apply non-None fields from ``payload`` onto a ``BotConfig`` (or instance.config)."""
+ cfg: BotConfig = target.config if isinstance(target, TutorBotInstance) else target
+ if payload.name is not None:
+ cfg.name = payload.name
+ if payload.description is not None:
+ cfg.description = payload.description
+ if payload.persona is not None:
+ cfg.persona = payload.persona
+ if payload.channels is not None:
+ cfg.channels = payload.channels
+ if payload.model is not None:
+ cfg.model = payload.model
@router.patch("/{bot_id}")
async def update_bot(bot_id: str, payload: UpdateBotRequest):
+ if payload.channels is not None:
+ _validate_channels_payload(payload.channels)
+
mgr = get_tutorbot_manager()
instance = mgr.get_bot(bot_id)
if instance:
- if payload.name is not None:
- instance.config.name = payload.name
- if payload.description is not None:
- instance.config.description = payload.description
- if payload.persona is not None:
- instance.config.persona = payload.persona
- if payload.channels is not None:
- instance.config.channels = payload.channels
- if payload.model is not None:
- instance.config.model = payload.model
-
+ _apply_payload(instance, payload)
mgr.save_bot_config(bot_id, instance.config)
if payload.channels is not None:
try:
await mgr.reload_channels(bot_id)
- except Exception:
+ except Exception as exc:
logger.exception("reload_channels failed for bot '%s'", bot_id)
raise HTTPException(
status_code=500,
- detail="Channels saved but failed to restart listeners; try stopping and starting the bot.",
+ detail=(
+ "Channels saved but failed to restart listeners "
+ f"({type(exc).__name__}); try stopping and starting the bot."
+ ),
) from None
- return instance.to_dict()
+ # NOTE: response masks secrets — front-end should re-fetch with
+ # ``?include_secrets=true`` if it needs the raw token to refill its form.
+ return instance.to_dict(mask_secrets=True)
cfg = mgr.load_bot_config(bot_id)
if not cfg:
raise HTTPException(status_code=404, detail="Bot not found")
- if payload.name is not None:
- cfg.name = payload.name
- if payload.description is not None:
- cfg.description = payload.description
- if payload.persona is not None:
- cfg.persona = payload.persona
- if payload.channels is not None:
- cfg.channels = payload.channels
- if payload.model is not None:
- cfg.model = payload.model
-
+ _apply_payload(cfg, payload)
mgr.save_bot_config(bot_id, cfg)
return _stopped_bot_dict(bot_id, cfg)
diff --git a/deeptutor/capabilities/deep_research.py b/deeptutor/capabilities/deep_research.py
index 47a220c71..928ebfba2 100644
--- a/deeptutor/capabilities/deep_research.py
+++ b/deeptutor/capabilities/deep_research.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import asyncio
from typing import Any
-
from deeptutor.capabilities.request_contracts import get_capability_request_schema
from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
from deeptutor.core.context import UnifiedContext
@@ -52,6 +51,37 @@ class DeepResearchCapability(BaseCapability):
else context.enabled_tools
)
request_config = validate_research_request_config(context.config_overrides)
+
+ # Consistency normalization: if "kb" is selected as a research source
+ # but no knowledge base is actually attached, drop "kb" from the
+ # effective sources. This avoids any code path falling through to a
+ # placeholder KB at the pipeline layer. If after the downgrade no
+ # source is left at all, surface a clear error to the user.
+ if "kb" in request_config.sources and not kb_name:
+ request_config = request_config.model_copy(
+ update={
+ "sources": [src for src in request_config.sources if src != "kb"],
+ }
+ )
+ await stream.progress(
+ message=(
+ "Knowledge base source was selected, but no knowledge "
+ "base is attached; KB retrieval is disabled for this "
+ "research run."
+ ),
+ source=self.name,
+ stage="rephrasing",
+ metadata={"trace_kind": "warning", "reason": "kb_without_kb_name"},
+ )
+ if not request_config.sources:
+ await stream.error(
+ "Deep research requires at least one source. Please "
+ "either attach a knowledge base or enable web/papers "
+ "sources.",
+ source=self.name,
+ )
+ return
+
config = build_research_runtime_config(
base_config=load_config_with_main("main.yaml"),
request_config=request_config,
diff --git a/deeptutor/capabilities/deep_solve.py b/deeptutor/capabilities/deep_solve.py
index 8c0e3e139..423591b50 100644
--- a/deeptutor/capabilities/deep_solve.py
+++ b/deeptutor/capabilities/deep_solve.py
@@ -40,7 +40,7 @@ class DeepSolveCapability(BaseCapability):
llm_config = get_llm_config()
detailed = context.config_overrides.get("detailed_answer", True)
- enabled_tools = (
+ enabled_tools = list(
self.manifest.tools_used
if context.enabled_tools is None
else context.enabled_tools
@@ -52,13 +52,29 @@ class DeepSolveCapability(BaseCapability):
else None
)
+ # Consistency normalization: if rag is requested but no KB is
+ # actually available, strip "rag" from the enabled tool set so the
+ # ReAct loop never exposes an action that would fail at runtime.
+ if rag_enabled and not kb_name:
+ enabled_tools = [tool for tool in enabled_tools if tool != "rag"]
+ rag_enabled = False
+ await stream.progress(
+ message=(
+ "RAG was enabled but no knowledge base is selected; "
+ "the rag tool is disabled for this turn."
+ ),
+ source=self.name,
+ stage="planning",
+ metadata={"trace_kind": "warning", "reason": "rag_without_kb"},
+ )
+
solver = MainSolver(
api_key=llm_config.api_key,
base_url=llm_config.base_url,
api_version=llm_config.api_version,
kb_name=kb_name,
language=context.language,
- enabled_tools=list(enabled_tools),
+ enabled_tools=enabled_tools,
disable_planner_retrieve=not (rag_enabled and kb_name),
)
await solver.ainit()
diff --git a/deeptutor/knowledge/initializer.py b/deeptutor/knowledge/initializer.py
index d621e01a7..d50a16e54 100644
--- a/deeptutor/knowledge/initializer.py
+++ b/deeptutor/knowledge/initializer.py
@@ -13,8 +13,8 @@ import shutil
from typing import Optional
from deeptutor.logging import get_logger
-from deeptutor.services.rag.components.routing import FileTypeRouter
-from deeptutor.services.rag.factory import DEFAULT_PROVIDER, normalize_provider_name
+from deeptutor.services.rag.file_routing import FileTypeRouter
+from deeptutor.services.rag.factory import DEFAULT_PROVIDER
from deeptutor.services.rag.service import RAGService
from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
@@ -44,7 +44,7 @@ class KnowledgeBaseInitializer:
self.api_key = api_key
self.base_url = base_url
self.progress_tracker = progress_tracker or ProgressTracker(kb_name, self.base_dir)
- self.rag_provider = normalize_provider_name(rag_provider or DEFAULT_PROVIDER)
+ self.rag_provider = DEFAULT_PROVIDER
def _register_to_config(self) -> None:
"""Register KB in kb_config.json with initializing state."""
@@ -85,7 +85,7 @@ class KnowledgeBaseInitializer:
except Exception:
metadata = {}
- metadata["rag_provider"] = normalize_provider_name(provider)
+ metadata["rag_provider"] = DEFAULT_PROVIDER
metadata["last_updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(metadata_file, "w", encoding="utf-8") as f:
@@ -152,7 +152,7 @@ class KnowledgeBaseInitializer:
)
doc_files: list[Path] = []
- for pattern in FileTypeRouter.get_glob_patterns_for_provider(provider):
+ for pattern in FileTypeRouter.get_glob_patterns():
doc_files.extend(list(self.raw_dir.glob(pattern)))
if not doc_files:
@@ -319,7 +319,7 @@ async def main() -> None:
if args.docs_dir:
docs_dir = Path(args.docs_dir)
if docs_dir.exists() and docs_dir.is_dir():
- for pattern in FileTypeRouter.get_glob_patterns_for_provider(DEFAULT_PROVIDER):
+ for pattern in FileTypeRouter.get_glob_patterns():
doc_files.extend([str(f) for f in docs_dir.glob(pattern)])
initializer = KnowledgeBaseInitializer(
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index ae4773653..32b04f68d 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -15,9 +15,9 @@ import shutil
import sys
from deeptutor.logging import get_logger
-from deeptutor.services.rag.components.routing import FileTypeRouter
+from deeptutor.services.rag.file_routing import FileTypeRouter
-from deeptutor.services.rag.factory import DEFAULT_PROVIDER, LEGACY_PROVIDER_ALIASES, normalize_provider_name
+from deeptutor.services.rag.factory import DEFAULT_PROVIDER
logger = get_logger("KnowledgeBaseManager")
@@ -157,14 +157,13 @@ class KnowledgeBaseManager:
continue
raw_provider = kb_entry.get("rag_provider")
- normalized_provider = normalize_provider_name(raw_provider or DEFAULT_PROVIDER)
- if kb_entry.get("rag_provider") != normalized_provider:
- kb_entry["rag_provider"] = normalized_provider
+ if kb_entry.get("rag_provider") != DEFAULT_PROVIDER:
+ kb_entry["rag_provider"] = DEFAULT_PROVIDER
config_changed = True
if (
isinstance(raw_provider, str)
- and raw_provider.strip().lower() in LEGACY_PROVIDER_ALIASES
+ and raw_provider.strip().lower() not in {"", DEFAULT_PROVIDER}
):
if not kb_entry.get("needs_reindex", False):
kb_entry["needs_reindex"] = True
@@ -348,8 +347,8 @@ class KnowledgeBaseManager:
kb_entry["description"] = metadata["description"]
if metadata.get("rag_provider"):
raw_provider = str(metadata["rag_provider"]).strip().lower()
- kb_entry["rag_provider"] = normalize_provider_name(raw_provider)
- if str(raw_provider).strip().lower() in LEGACY_PROVIDER_ALIASES:
+ kb_entry["rag_provider"] = DEFAULT_PROVIDER
+ if raw_provider not in {"", DEFAULT_PROVIDER}:
kb_entry["needs_reindex"] = True
if metadata.get("created_at"):
kb_entry["created_at"] = metadata["created_at"]
@@ -504,7 +503,7 @@ class KnowledgeBaseManager:
metadata = {
"name": kb_name,
"description": kb_config.get("description", f"Knowledge base: {kb_name}"),
- "rag_provider": normalize_provider_name(kb_config.get("rag_provider")),
+ "rag_provider": DEFAULT_PROVIDER,
"needs_reindex": bool(kb_config.get("needs_reindex", False)),
"created_at": kb_config.get("created_at"),
"last_updated": kb_config.get("updated_at"),
@@ -540,7 +539,7 @@ class KnowledgeBaseManager:
status = kb_config.get("status")
progress = kb_config.get("progress")
description = kb_config.get("description", f"Knowledge base: {kb_name}")
- rag_provider = normalize_provider_name(kb_config.get("rag_provider"))
+ rag_provider = DEFAULT_PROVIDER
needs_reindex = bool(kb_config.get("needs_reindex", False))
created_at = kb_config.get("created_at")
updated_at = kb_config.get("updated_at")
@@ -748,13 +747,7 @@ class KnowledgeBaseManager:
if not folder.is_dir():
raise ValueError(f"Path is not a directory: {folder}")
- # Get RAG provider from kb_config.json to determine supported extensions
- self.config = self._load_config()
- kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})
- provider = normalize_provider_name(kb_config.get("rag_provider") or DEFAULT_PROVIDER)
-
- # Get supported files in folder based on provider
- supported_extensions = FileTypeRouter.get_extensions_for_provider(provider)
+ supported_extensions = FileTypeRouter.get_supported_extensions()
files: list[Path] = []
for ext in supported_extensions:
files.extend(folder.glob(f"**/*{ext}"))
@@ -885,7 +878,7 @@ class KnowledgeBaseManager:
if not folder.exists() or not folder.is_dir():
return []
- supported_extensions = FileTypeRouter.get_extensions_for_provider(provider)
+ supported_extensions = FileTypeRouter.get_supported_extensions()
files = []
for ext in supported_extensions:
@@ -930,13 +923,7 @@ class KnowledgeBaseManager:
except Exception:
pass
- # Get RAG provider from kb_config.json to determine supported extensions
- self.config = self._load_config()
- kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})
- provider = normalize_provider_name(kb_config.get("rag_provider") or DEFAULT_PROVIDER)
-
- # Scan current files based on provider's supported extensions
- supported_extensions = FileTypeRouter.get_extensions_for_provider(provider)
+ supported_extensions = FileTypeRouter.get_supported_extensions()
new_files = []
modified_files = []
diff --git a/deeptutor/logging/config.py b/deeptutor/logging/config.py
index e70c3add8..fb3ec8bcb 100644
--- a/deeptutor/logging/config.py
+++ b/deeptutor/logging/config.py
@@ -8,7 +8,7 @@ A single `level` parameter controls all logging (including RAG modules).
from dataclasses import dataclass
from pathlib import Path
-from typing import Dict, Optional
+from typing import Optional
@dataclass
@@ -25,9 +25,6 @@ class LoggingConfig:
# Log directory (relative to project root or absolute)
log_dir: Optional[str] = None
- # RAG module logger name mapping
- rag_logger_names: Optional[Dict[str, str]] = None
-
# File rotation settings
max_bytes: int = 10 * 1024 * 1024 # 10MB
backup_count: int = 5
@@ -76,7 +73,6 @@ def load_logging_config() -> LoggingConfig:
console_output=logging_config.get("console_output", True),
file_output=logging_config.get("save_to_file", True),
log_dir=get_path_from_config(config, "user_log_dir"),
- rag_logger_names=logging_config.get("rag_logger_names"),
)
except Exception:
return LoggingConfig()
diff --git a/deeptutor/services/__init__.py b/deeptutor/services/__init__.py
index 167b90c3e..0d903e45f 100644
--- a/deeptutor/services/__init__.py
+++ b/deeptutor/services/__init__.py
@@ -14,7 +14,7 @@ Unified service layer for DeepTutor providing:
Usage:
from deeptutor.services.llm import get_llm_client
from deeptutor.services.embedding import get_embedding_client
- from deeptutor.services.rag import get_pipeline
+ from deeptutor.services.rag import RAGService
from deeptutor.services.prompt import get_prompt_manager
from deeptutor.services.search import web_search
from deeptutor.services.setup import init_user_directories
@@ -28,9 +28,9 @@ Usage:
embed = get_embedding_client()
vectors = await embed.embed(["text1", "text2"])
- # RAG
- pipeline = get_pipeline("llamaindex")
- result = await pipeline.search("query", "kb_name")
+ # RAG (LlamaIndex backend)
+ rag = RAGService()
+ result = await rag.search("query", kb_name="my_kb")
# Prompt
pm = get_prompt_manager()
diff --git a/deeptutor/services/config/knowledge_base_config.py b/deeptutor/services/config/knowledge_base_config.py
index fb878b0d1..fe0510b4d 100644
--- a/deeptutor/services/config/knowledge_base_config.py
+++ b/deeptutor/services/config/knowledge_base_config.py
@@ -5,11 +5,7 @@ from pathlib import Path
from typing import Any
from deeptutor.logging import get_logger
-from deeptutor.services.rag.factory import (
- DEFAULT_PROVIDER,
- LEGACY_PROVIDER_ALIASES,
- normalize_provider_name,
-)
+from deeptutor.services.rag.factory import DEFAULT_PROVIDER
from deeptutor.services.path_service import get_path_service
logger = get_logger("KBConfigService")
@@ -58,7 +54,7 @@ class KnowledgeBaseConfigService:
def _normalize_payload(self, payload: dict[str, Any]) -> dict[str, Any]:
defaults = payload.setdefault("defaults", _default_payload()["defaults"])
- defaults["rag_provider"] = normalize_provider_name(defaults.get("rag_provider"))
+ defaults["rag_provider"] = DEFAULT_PROVIDER
knowledge_bases = payload.setdefault("knowledge_bases", {})
kb_base_dir = self.config_path.parent
@@ -67,10 +63,9 @@ class KnowledgeBaseConfigService:
continue
raw_provider = config.get("rag_provider")
- normalized = normalize_provider_name(raw_provider or defaults["rag_provider"])
- config["rag_provider"] = normalized
+ config["rag_provider"] = DEFAULT_PROVIDER
- if isinstance(raw_provider, str) and raw_provider.strip().lower() in LEGACY_PROVIDER_ALIASES:
+ if isinstance(raw_provider, str) and raw_provider.strip().lower() not in {"", DEFAULT_PROVIDER}:
config["needs_reindex"] = True
kb_dir = kb_base_dir / kb_name
@@ -101,13 +96,12 @@ class KnowledgeBaseConfigService:
kb_config = dict(self._config.get("knowledge_bases", {}).get(kb_name, {}))
merged = {
"default_kb": defaults.get("default_kb"),
- "rag_provider": normalize_provider_name(
- kb_config.get("rag_provider") or defaults.get("rag_provider", DEFAULT_PROVIDER)
- ),
+ "rag_provider": DEFAULT_PROVIDER,
"search_mode": kb_config.get("search_mode") or defaults.get("search_mode", "hybrid"),
"needs_reindex": bool(kb_config.get("needs_reindex", False)),
**kb_config,
}
+ merged["rag_provider"] = DEFAULT_PROVIDER
return merged
def set_kb_config(self, kb_name: str, config: dict[str, Any]) -> None:
@@ -116,15 +110,10 @@ class KnowledgeBaseConfigService:
self._save()
def get_rag_provider(self, kb_name: str) -> str:
- return str(self.get_kb_config(kb_name).get("rag_provider", DEFAULT_PROVIDER))
+ return DEFAULT_PROVIDER
def set_rag_provider(self, kb_name: str, provider: str) -> None:
- self.set_kb_config(
- kb_name,
- {
- "rag_provider": normalize_provider_name(provider),
- },
- )
+ self.set_kb_config(kb_name, {"rag_provider": DEFAULT_PROVIDER})
def get_search_mode(self, kb_name: str) -> str:
return str(self.get_kb_config(kb_name).get("search_mode", "hybrid"))
@@ -166,8 +155,8 @@ class KnowledgeBaseConfigService:
config: dict[str, Any] = {}
if metadata.get("rag_provider"):
raw_provider = metadata["rag_provider"]
- config["rag_provider"] = normalize_provider_name(raw_provider)
- if str(raw_provider).strip().lower() in LEGACY_PROVIDER_ALIASES:
+ config["rag_provider"] = DEFAULT_PROVIDER
+ if str(raw_provider).strip().lower() not in {"", DEFAULT_PROVIDER}:
config["needs_reindex"] = True
if metadata.get("search_mode"):
config["search_mode"] = metadata["search_mode"]
diff --git a/deeptutor/services/rag/__init__.py b/deeptutor/services/rag/__init__.py
index 6871ae967..2db090fe3 100644
--- a/deeptutor/services/rag/__init__.py
+++ b/deeptutor/services/rag/__init__.py
@@ -3,14 +3,11 @@
from .factory import (
DEFAULT_PROVIDER,
get_pipeline,
- has_pipeline,
list_pipelines,
normalize_provider_name,
- register_pipeline,
)
-from .pipeline import RAGPipeline
+from .file_routing import DocumentType, FileClassification, FileTypeRouter
from .service import RAGService
-from .types import Chunk, Document, SearchResult
def __getattr__(name: str):
@@ -24,14 +21,11 @@ def __getattr__(name: str):
__all__ = [
"RAGService",
- "Document",
- "Chunk",
- "SearchResult",
- "RAGPipeline",
+ "FileTypeRouter",
+ "FileClassification",
+ "DocumentType",
"get_pipeline",
"list_pipelines",
- "register_pipeline",
- "has_pipeline",
"normalize_provider_name",
"DEFAULT_PROVIDER",
"LlamaIndexPipeline",
diff --git a/deeptutor/services/rag/components/__init__.py b/deeptutor/services/rag/components/__init__.py
deleted file mode 100644
index aa9ef36b5..000000000
--- a/deeptutor/services/rag/components/__init__.py
+++ /dev/null
@@ -1,29 +0,0 @@
-"""
-RAG Components
-==============
-
-Modular components for building RAG pipelines.
-
-Components follow a simple protocol:
-- Each component has a `name` attribute
-- Each component has an async `process()` method
-"""
-
-# Import component modules for convenience
-from . import chunkers, embedders, indexers, parsers, retrievers
-from .base import BaseComponent, Component
-from .routing import DocumentType, FileClassification, FileTypeRouter
-
-__all__ = [
- "Component",
- "BaseComponent",
- "parsers",
- "chunkers",
- "embedders",
- "indexers",
- "retrievers",
- # File type routing
- "FileTypeRouter",
- "FileClassification",
- "DocumentType",
-]
diff --git a/deeptutor/services/rag/components/base.py b/deeptutor/services/rag/components/base.py
deleted file mode 100644
index 8f3b6ea49..000000000
--- a/deeptutor/services/rag/components/base.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""
-Base Component
-==============
-
-Base classes and protocols for RAG components.
-"""
-
-from typing import Any, Protocol, runtime_checkable
-
-
-@runtime_checkable
-class Component(Protocol):
- """
- Base protocol for all RAG components.
-
- All components must implement:
- - name: str - Component identifier
- - process(data, **kwargs) -> Any - Process input data
- """
-
- name: str
-
- async def process(self, data: Any, **kwargs) -> Any:
- """
- Process input data.
-
- Args:
- data: Input data to process
- **kwargs: Additional arguments
-
- Returns:
- Processed output
- """
- ...
-
-
-class BaseComponent:
- """
- Base class with common functionality for components.
-
- Provides:
- - Logger initialization
- - Default name from class name
- """
-
- name: str = "base"
-
- def __init__(self):
- from deeptutor.logging import get_logger
-
- self.logger = get_logger(self.__class__.__name__)
-
- async def process(self, data: Any, **kwargs) -> Any:
- """
- Process input data.
-
- Override this method in subclasses.
- """
- raise NotImplementedError("Subclasses must implement process()")
diff --git a/deeptutor/services/rag/components/chunkers/__init__.py b/deeptutor/services/rag/components/chunkers/__init__.py
deleted file mode 100644
index 0d6c04ebd..000000000
--- a/deeptutor/services/rag/components/chunkers/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-"""
-Document Chunkers
-=================
-
-Chunkers for splitting documents into smaller pieces.
-"""
-
-from .base import BaseChunker
-from .fixed import FixedSizeChunker
-from .numbered_item import NumberedItemExtractor
-from .semantic import SemanticChunker
-
-__all__ = [
- "BaseChunker",
- "SemanticChunker",
- "FixedSizeChunker",
- "NumberedItemExtractor",
-]
diff --git a/deeptutor/services/rag/components/chunkers/base.py b/deeptutor/services/rag/components/chunkers/base.py
deleted file mode 100644
index 06e0e4ca9..000000000
--- a/deeptutor/services/rag/components/chunkers/base.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""
-Base Chunker
-============
-
-Base class for document chunkers.
-"""
-
-from typing import List
-
-from ...types import Chunk, Document
-from ..base import BaseComponent
-
-
-class BaseChunker(BaseComponent):
- """
- Base class for document chunkers.
-
- Chunkers split documents into smaller chunks for processing.
- """
-
- name = "base_chunker"
-
- async def process(self, doc: Document, **kwargs) -> List[Chunk]:
- """
- Chunk a document.
-
- Args:
- doc: Document to chunk
- **kwargs: Additional arguments
-
- Returns:
- List of Chunks
- """
- raise NotImplementedError("Subclasses must implement process()")
diff --git a/deeptutor/services/rag/components/chunkers/fixed.py b/deeptutor/services/rag/components/chunkers/fixed.py
deleted file mode 100644
index 441de453e..000000000
--- a/deeptutor/services/rag/components/chunkers/fixed.py
+++ /dev/null
@@ -1,71 +0,0 @@
-"""
-Fixed Size Chunker
-==================
-
-Chunker that splits documents into fixed-size pieces.
-"""
-
-from typing import List
-
-from ...types import Chunk, Document
-from ..base import BaseComponent
-
-
-class FixedSizeChunker(BaseComponent):
- """
- Fixed-size chunker.
-
- Splits documents into chunks of a fixed size with optional overlap.
- """
-
- name = "fixed_size_chunker"
-
- def __init__(self, chunk_size: int = 1000, chunk_overlap: int = 100):
- """
- Initialize fixed-size chunker.
-
- Args:
- chunk_size: Size of each chunk in characters
- chunk_overlap: Overlap between chunks
- """
- super().__init__()
- self.chunk_size = chunk_size
- self.chunk_overlap = chunk_overlap
-
- async def process(self, doc: Document, **kwargs) -> List[Chunk]:
- """
- Chunk a document into fixed-size pieces.
-
- Args:
- doc: Document to chunk
- **kwargs: Additional arguments
-
- Returns:
- List of fixed-size Chunks
- """
- self.logger.info(f"Chunking document: {doc.file_path or 'inline'}")
-
- text = doc.content
- if not text:
- return []
-
- chunks = []
- step = self.chunk_size - self.chunk_overlap
-
- for i in range(0, len(text), step):
- chunk_text = text[i : i + self.chunk_size].strip()
- if chunk_text:
- chunks.append(
- Chunk(
- content=chunk_text,
- chunk_type="text",
- metadata={
- "start_pos": i,
- "end_pos": min(i + self.chunk_size, len(text)),
- "source": doc.file_path,
- },
- )
- )
-
- self.logger.info(f"Created {len(chunks)} chunks")
- return chunks
diff --git a/deeptutor/services/rag/components/chunkers/numbered_item.py b/deeptutor/services/rag/components/chunkers/numbered_item.py
deleted file mode 100644
index c62755df7..000000000
--- a/deeptutor/services/rag/components/chunkers/numbered_item.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""
-Numbered Item Extractor
-=======================
-
-Extracts numbered items (definitions, theorems, equations) from documents.
-"""
-
-from typing import List
-
-from ...types import Chunk, Document
-from ..base import BaseComponent
-
-
-class NumberedItemExtractor(BaseComponent):
- """
- Extract numbered items (definitions, theorems, equations) from documents.
-
- Uses LLM to identify and extract structured academic content like
- definitions, theorems, lemmas, propositions, equations, etc.
- """
-
- name = "numbered_item_extractor"
-
- def __init__(self, batch_size: int = 20, max_concurrent: int = 5):
- """
- Initialize numbered item extractor.
-
- Args:
- batch_size: Number of content items to process per batch
- max_concurrent: Maximum concurrent LLM calls
- """
- super().__init__()
- self.batch_size = batch_size
- self.max_concurrent = max_concurrent
-
- async def process(self, doc: Document, **kwargs) -> List[Chunk]:
- """
- Extract numbered items from a document.
-
- Args:
- doc: Document to extract from (must have content_items)
- **kwargs: Additional arguments
-
- Returns:
- List of Chunks representing numbered items
- """
- if not doc.content_items:
- self.logger.warning("No content_items in document, skipping extraction")
- return []
-
- _ = kwargs
- self.logger.info(
- "Numbered item extraction is deprecated and disabled in llamaindex-only mode; skipping"
- )
- return []
diff --git a/deeptutor/services/rag/components/chunkers/semantic.py b/deeptutor/services/rag/components/chunkers/semantic.py
deleted file mode 100644
index ae77d8924..000000000
--- a/deeptutor/services/rag/components/chunkers/semantic.py
+++ /dev/null
@@ -1,97 +0,0 @@
-"""
-Semantic Chunker
-================
-
-Chunker that splits documents based on semantic boundaries.
-"""
-
-from typing import List
-
-from ...types import Chunk, Document
-from ..base import BaseComponent
-
-
-class SemanticChunker(BaseComponent):
- """
- Semantic chunker.
-
- Splits documents based on semantic boundaries like paragraphs,
- sections, or natural breakpoints.
- """
-
- name = "semantic_chunker"
-
- def __init__(
- self,
- chunk_size: int = 1000,
- chunk_overlap: int = 200,
- separators: List[str] = None,
- ):
- """
- Initialize semantic chunker.
-
- Args:
- chunk_size: Target chunk size in characters
- chunk_overlap: Overlap between chunks
- separators: List of separators to split on
- """
- super().__init__()
- self.chunk_size = chunk_size
- self.chunk_overlap = chunk_overlap
- self.separators = separators or ["\n\n", "\n", ". ", " "]
-
- async def process(self, doc: Document, **kwargs) -> List[Chunk]:
- """
- Chunk a document semantically.
-
- Args:
- doc: Document to chunk
- **kwargs: Additional arguments
-
- Returns:
- List of semantic Chunks
- """
- self.logger.info(f"Chunking document: {doc.file_path or 'inline'}")
-
- text = doc.content
- if not text:
- return []
-
- chunks = []
- current_pos = 0
-
- while current_pos < len(text):
- # Find chunk end
- end_pos = min(current_pos + self.chunk_size, len(text))
-
- # Try to find a natural break point
- if end_pos < len(text):
- for sep in self.separators:
- # Look for separator in the last portion of the chunk
- search_start = max(current_pos + self.chunk_size - 200, current_pos)
- sep_pos = text.rfind(sep, search_start, end_pos)
- if sep_pos > current_pos:
- end_pos = sep_pos + len(sep)
- break
-
- chunk_text = text[current_pos:end_pos].strip()
- if chunk_text:
- chunks.append(
- Chunk(
- content=chunk_text,
- chunk_type="text",
- metadata={
- "start_pos": current_pos,
- "end_pos": end_pos,
- "source": doc.file_path,
- },
- )
- )
-
- # Move to next position with overlap
- current_pos = end_pos - self.chunk_overlap
- if current_pos >= len(text) - self.chunk_overlap:
- break
-
- self.logger.info(f"Created {len(chunks)} chunks")
- return chunks
diff --git a/deeptutor/services/rag/components/embedders/__init__.py b/deeptutor/services/rag/components/embedders/__init__.py
deleted file mode 100644
index 0102d8061..000000000
--- a/deeptutor/services/rag/components/embedders/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Document Embedders
-==================
-
-Embedders for generating vector representations of text.
-"""
-
-from .base import BaseEmbedder
-from .openai import OpenAIEmbedder
-
-__all__ = [
- "BaseEmbedder",
- "OpenAIEmbedder",
-]
diff --git a/deeptutor/services/rag/components/embedders/base.py b/deeptutor/services/rag/components/embedders/base.py
deleted file mode 100644
index 9eff02fee..000000000
--- a/deeptutor/services/rag/components/embedders/base.py
+++ /dev/null
@@ -1,32 +0,0 @@
-"""
-Base Embedder
-=============
-
-Base class for document embedders.
-"""
-
-from ...types import Document
-from ..base import BaseComponent
-
-
-class BaseEmbedder(BaseComponent):
- """
- Base class for document embedders.
-
- Embedders generate vector representations for document chunks.
- """
-
- name = "base_embedder"
-
- async def process(self, doc: Document, **kwargs) -> Document:
- """
- Embed a document's chunks.
-
- Args:
- doc: Document with chunks to embed
- **kwargs: Additional arguments
-
- Returns:
- Document with embedded chunks
- """
- raise NotImplementedError("Subclasses must implement process()")
diff --git a/deeptutor/services/rag/components/embedders/openai.py b/deeptutor/services/rag/components/embedders/openai.py
deleted file mode 100644
index dd65c7ef0..000000000
--- a/deeptutor/services/rag/components/embedders/openai.py
+++ /dev/null
@@ -1,63 +0,0 @@
-"""
-OpenAI Embedder
-===============
-
-Embedder using OpenAI-compatible embedding API.
-"""
-
-from ...types import Document
-from ..base import BaseComponent
-
-
-class OpenAIEmbedder(BaseComponent):
- """
- OpenAI-compatible embedder.
-
- Uses the embedding service to generate vectors for document chunks.
- """
-
- name = "openai_embedder"
-
- def __init__(self, batch_size: int = 100):
- """
- Initialize OpenAI embedder.
-
- Args:
- batch_size: Number of texts to embed per API call
- """
- super().__init__()
- self.batch_size = batch_size
-
- async def process(self, doc: Document, **kwargs) -> Document:
- """
- Embed a document's chunks.
-
- Args:
- doc: Document with chunks to embed
- **kwargs: Additional arguments
-
- Returns:
- Document with embedded chunks
- """
- if not doc.chunks:
- self.logger.warning("No chunks to embed")
- return doc
-
- self.logger.info(f"Embedding {len(doc.chunks)} chunks")
-
- from deeptutor.services.embedding import get_embedding_client
-
- client = get_embedding_client()
-
- # Batch embed
- for i in range(0, len(doc.chunks), self.batch_size):
- batch = doc.chunks[i : i + self.batch_size]
- texts = [chunk.content for chunk in batch]
-
- embeddings = await client.embed(texts)
-
- for chunk, embedding in zip(batch, embeddings):
- chunk.embedding = embedding
-
- self.logger.info("Embedding complete")
- return doc
diff --git a/deeptutor/services/rag/components/indexers/__init__.py b/deeptutor/services/rag/components/indexers/__init__.py
deleted file mode 100644
index 8d0fc858d..000000000
--- a/deeptutor/services/rag/components/indexers/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-"""Document indexers."""
-
-from .base import BaseIndexer
-from .vector import VectorIndexer
-
-__all__ = [
- "BaseIndexer",
- "VectorIndexer",
-]
diff --git a/deeptutor/services/rag/components/indexers/base.py b/deeptutor/services/rag/components/indexers/base.py
deleted file mode 100644
index ee61725e7..000000000
--- a/deeptutor/services/rag/components/indexers/base.py
+++ /dev/null
@@ -1,35 +0,0 @@
-"""
-Base Indexer
-============
-
-Base class for document indexers.
-"""
-
-from typing import List
-
-from ...types import Document
-from ..base import BaseComponent
-
-
-class BaseIndexer(BaseComponent):
- """
- Base class for document indexers.
-
- Indexers build searchable indexes from documents.
- """
-
- name = "base_indexer"
-
- async def process(self, kb_name: str, documents: List[Document], **kwargs) -> bool:
- """
- Index documents into a knowledge base.
-
- Args:
- kb_name: Knowledge base name
- documents: List of documents to index
- **kwargs: Additional arguments
-
- Returns:
- True if successful
- """
- raise NotImplementedError("Subclasses must implement process()")
diff --git a/deeptutor/services/rag/components/indexers/vector.py b/deeptutor/services/rag/components/indexers/vector.py
deleted file mode 100644
index a06228d7a..000000000
--- a/deeptutor/services/rag/components/indexers/vector.py
+++ /dev/null
@@ -1,157 +0,0 @@
-"""
-Vector Indexer
-==============
-
-Vector-based indexer using dense embeddings with FAISS.
-Provides fast similarity search for RAG retrieval.
-"""
-
-import json
-from pathlib import Path
-import pickle
-from typing import List, Optional
-
-try:
- import numpy as np
-except ImportError: # pragma: no cover - optional dependency in minimal envs
- np = None
-
-from ...types import Document
-from ..base import BaseComponent
-
-
-class VectorIndexer(BaseComponent):
- """
- Vector indexer using FAISS for fast similarity search.
-
- Creates and stores vector embeddings for efficient retrieval.
- Falls back to simple vector storage if FAISS is not available.
- """
-
- name = "vector_indexer"
-
- def __init__(self, kb_base_dir: Optional[str] = None):
- """
- Initialize vector indexer.
-
- Args:
- kb_base_dir: Base directory for knowledge bases
- """
- super().__init__()
- self.kb_base_dir = kb_base_dir or str(
- Path(__file__).resolve().parent.parent.parent.parent.parent.parent
- / "data"
- / "knowledge_bases"
- )
-
- # Try to import FAISS, fallback to simple storage if not available
- self.use_faiss = False
- if np is None:
- self.logger.warning("NumPy not available, vector indexer is disabled")
- return
-
- try:
- import faiss
-
- self.faiss = faiss
- self.use_faiss = True
- self.logger.info("Using FAISS for vector indexing")
- except ImportError:
- self.logger.warning("FAISS not available, using simple vector storage")
-
- async def process(self, kb_name: str, documents: List[Document], **kwargs) -> bool:
- """
- Index documents using vector embeddings.
-
- Creates FAISS index for fast similarity search or falls back to
- simple JSON storage if FAISS is unavailable.
-
- Args:
- kb_name: Knowledge base name
- documents: List of documents to index
- **kwargs: Additional arguments
-
- Returns:
- True if successful
- """
- self.logger.info(f"Indexing {len(documents)} documents into vector store for {kb_name}")
-
- # Collect all chunks with embeddings
- all_chunks = []
- for doc in documents:
- for chunk in doc.chunks:
- # Check if embedding exists (handles numpy arrays and lists)
- if chunk.embedding is not None and len(chunk.embedding) > 0:
- all_chunks.append(chunk)
-
- if not all_chunks:
- self.logger.warning("No chunks with embeddings to index")
- return False
-
- self.logger.info(f"Indexing {len(all_chunks)} chunks")
-
- # Create vector store directory
- kb_dir = Path(self.kb_base_dir) / kb_name / "vector_store"
- kb_dir.mkdir(parents=True, exist_ok=True)
-
- # Convert embeddings to numpy array
- if np is None:
- self.logger.warning("NumPy not available, skipping vector indexing")
- return False
-
- embeddings = np.array(
- [
- chunk.embedding if isinstance(chunk.embedding, list) else chunk.embedding.tolist()
- for chunk in all_chunks
- ],
- dtype=np.float32,
- )
-
- # Store metadata separately
- metadata = []
- for i, chunk in enumerate(all_chunks):
- metadata.append(
- {
- "id": i,
- "content": chunk.content,
- "type": chunk.chunk_type,
- "metadata": chunk.metadata,
- }
- )
-
- # Save metadata
- with open(kb_dir / "metadata.json", "w", encoding="utf-8") as f:
- json.dump(metadata, f, ensure_ascii=False, indent=2)
-
- if self.use_faiss:
- # Create FAISS index for inner product (cosine similarity with normalized vectors)
- dimension = embeddings.shape[1]
- index = self.faiss.IndexFlatIP(dimension) # Inner product for cosine similarity
-
- # Normalize vectors for cosine similarity (inner product of normalized vectors = cosine similarity)
- self.faiss.normalize_L2(embeddings)
-
- # Add vectors to index
- index.add(embeddings)
-
- # Save FAISS index
- self.faiss.write_index(index, str(kb_dir / "index.faiss"))
- self.logger.info(f"FAISS index saved with {index.ntotal} vectors")
- else:
- # Simple storage: save embeddings as pickle
- with open(kb_dir / "embeddings.pkl", "wb") as f:
- pickle.dump(embeddings, f)
- self.logger.info(f"Embeddings saved for {len(all_chunks)} chunks")
-
- # Save index info
- info = {
- "num_chunks": len(all_chunks),
- "num_documents": len(documents),
- "embedding_dim": embeddings.shape[1],
- "use_faiss": self.use_faiss,
- }
- with open(kb_dir / "info.json", "w", encoding="utf-8") as f:
- json.dump(info, f, indent=2)
-
- self.logger.info(f"Vector index saved to {kb_dir}")
- return True
diff --git a/deeptutor/services/rag/components/parsers/__init__.py b/deeptutor/services/rag/components/parsers/__init__.py
deleted file mode 100644
index 9b50b2f43..000000000
--- a/deeptutor/services/rag/components/parsers/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-"""
-Document Parsers
-================
-
-Parsers for extracting content from various document formats.
-"""
-
-from .base import BaseParser
-from .markdown import MarkdownParser
-from .pdf import PDFParser
-from .text import TextParser
-
-__all__ = [
- "BaseParser",
- "PDFParser",
- "MarkdownParser",
- "TextParser",
-]
diff --git a/deeptutor/services/rag/components/parsers/base.py b/deeptutor/services/rag/components/parsers/base.py
deleted file mode 100644
index 026f43d15..000000000
--- a/deeptutor/services/rag/components/parsers/base.py
+++ /dev/null
@@ -1,35 +0,0 @@
-"""
-Base Parser
-===========
-
-Base class for document parsers.
-"""
-
-from pathlib import Path
-from typing import Union
-
-from ...types import Document
-from ..base import BaseComponent
-
-
-class BaseParser(BaseComponent):
- """
- Base class for document parsers.
-
- Parsers convert raw files into Document objects.
- """
-
- name = "base_parser"
-
- async def process(self, file_path: Union[str, Path], **kwargs) -> Document:
- """
- Parse a file into a Document.
-
- Args:
- file_path: Path to the file to parse
- **kwargs: Additional arguments
-
- Returns:
- Parsed Document
- """
- raise NotImplementedError("Subclasses must implement process()")
diff --git a/deeptutor/services/rag/components/parsers/markdown.py b/deeptutor/services/rag/components/parsers/markdown.py
deleted file mode 100644
index 790768371..000000000
--- a/deeptutor/services/rag/components/parsers/markdown.py
+++ /dev/null
@@ -1,52 +0,0 @@
-"""
-Markdown Parser
-===============
-
-Parser for Markdown documents.
-"""
-
-from pathlib import Path
-from typing import Union
-
-from ...types import Document
-from ..base import BaseComponent
-
-
-class MarkdownParser(BaseComponent):
- """
- Markdown parser.
-
- Parses Markdown files into Document objects.
- """
-
- name = "markdown_parser"
-
- async def process(self, file_path: Union[str, Path], **kwargs) -> Document:
- """
- Parse a Markdown file into a Document.
-
- Args:
- file_path: Path to the Markdown file
- **kwargs: Additional arguments
-
- Returns:
- Parsed Document
- """
- file_path = Path(file_path)
-
- if not file_path.exists():
- raise FileNotFoundError(f"Markdown file not found: {file_path}")
-
- self.logger.info(f"Parsing Markdown: {file_path.name}")
-
- with open(file_path, "r", encoding="utf-8") as f:
- content = f.read()
-
- return Document(
- content=content,
- file_path=str(file_path),
- metadata={
- "filename": file_path.name,
- "parser": self.name,
- },
- )
diff --git a/deeptutor/services/rag/components/parsers/pdf.py b/deeptutor/services/rag/components/parsers/pdf.py
deleted file mode 100644
index 03f001435..000000000
--- a/deeptutor/services/rag/components/parsers/pdf.py
+++ /dev/null
@@ -1,111 +0,0 @@
-"""
-PDF Parser
-==========
-
-Parser for PDF documents.
-"""
-
-import json
-from pathlib import Path
-from typing import Optional, Union
-
-from ...types import Document
-from ..base import BaseComponent
-
-
-class PDFParser(BaseComponent):
- """
- PDF parser for extraction.
- """
-
- name = "pdf_parser"
-
- def __init__(self, output_dir: Optional[str] = None):
- """
- Initialize PDF parser.
-
- Args:
- output_dir: Directory to store parsed output
- """
- super().__init__()
- self.output_dir = output_dir
-
- async def process(self, file_path: Union[str, Path], **kwargs) -> Document:
- """
- Parse a PDF file into a Document.
-
- Args:
- file_path: Path to the PDF file
- **kwargs: Additional arguments
-
- Returns:
- Parsed Document with content and content_items
- """
- file_path = Path(file_path)
-
- if not file_path.exists():
- raise FileNotFoundError(f"PDF file not found: {file_path}")
-
- self.logger.info(f"Parsing PDF: {file_path.name}")
-
- # Check for existing parsed content
- output_dir = Path(kwargs.get("output_dir", self.output_dir or file_path.parent))
- content_list_file = output_dir / f"{file_path.stem}.json"
-
- content_items = []
- content = ""
-
- if content_list_file.exists():
- # Load existing parsed content
- self.logger.info(f"Loading existing parsed content from {content_list_file}")
- with open(content_list_file, "r", encoding="utf-8") as f:
- content_items = json.load(f)
-
- # Extract text content
- content = self._extract_text_from_content_items(content_items)
- else:
- # Parse PDF with local fallback extraction
- self.logger.warning(
- "No pre-parsed content found. Falling back to local PDF text extraction."
- )
- # Basic text extraction fallback
- content = await self._basic_pdf_extract(file_path)
-
- return Document(
- content=content,
- file_path=str(file_path),
- content_items=content_items,
- metadata={
- "filename": file_path.name,
- "parser": self.name,
- },
- )
-
- def _extract_text_from_content_items(self, content_items: list) -> str:
- """Extract plain text from content-item payloads."""
- texts = []
- for item in content_items:
- if isinstance(item, dict):
- if "text" in item:
- texts.append(item["text"])
- elif "content" in item:
- texts.append(item["content"])
- return "\n\n".join(texts)
-
- async def _basic_pdf_extract(self, file_path: Path) -> str:
- """Basic PDF text extraction fallback."""
- try:
- import fitz # PyMuPDF
-
- doc = fitz.open(file_path)
- texts = []
- for page in doc:
- texts.append(page.get_text())
- doc.close()
- return "\n\n".join(texts)
- except ImportError:
- self.logger.warning("PyMuPDF not installed. Cannot extract PDF text.")
- return ""
- except Exception as e:
- self.logger.error(f"Failed to extract PDF text: {e}")
- return ""
diff --git a/deeptutor/services/rag/components/parsers/text.py b/deeptutor/services/rag/components/parsers/text.py
deleted file mode 100644
index 6d8fbaac7..000000000
--- a/deeptutor/services/rag/components/parsers/text.py
+++ /dev/null
@@ -1,86 +0,0 @@
-"""
-Text Parser
-===========
-
-Parser for plain text documents (.txt files).
-"""
-
-from pathlib import Path
-from typing import Union
-
-from ...types import Document
-from ..base import BaseComponent
-
-
-class TextParser(BaseComponent):
- """
- Plain text parser.
-
- Parses text files (.txt) into Document objects.
- Also handles common text-based formats.
- """
-
- name = "text_parser"
-
- # Supported extensions
- SUPPORTED_EXTENSIONS = {".txt", ".text", ".log", ".csv", ".tsv"}
-
- async def process(self, file_path: Union[str, Path], **kwargs) -> Document:
- """
- Parse a text file into a Document.
-
- Args:
- file_path: Path to the text file
- **kwargs: Additional arguments
-
- Returns:
- Parsed Document
- """
- file_path = Path(file_path)
-
- if not file_path.exists():
- raise FileNotFoundError(f"Text file not found: {file_path}")
-
- self.logger.info(f"Parsing text file: {file_path.name}")
-
- # Try different encodings
- content = None
- encodings = ["utf-8", "utf-8-sig", "gbk", "gb2312", "latin-1"]
-
- for encoding in encodings:
- try:
- with open(file_path, "r", encoding=encoding) as f:
- content = f.read()
- break
- except UnicodeDecodeError:
- continue
-
- if content is None:
- # Last resort: read as binary and decode with error handling
- with open(file_path, "rb") as f:
- content = f.read().decode("utf-8", errors="replace")
-
- return Document(
- content=content,
- file_path=str(file_path),
- metadata={
- "filename": file_path.name,
- "parser": self.name,
- "extension": file_path.suffix.lower(),
- "size_bytes": file_path.stat().st_size,
- },
- )
-
- @classmethod
- def can_parse(cls, file_path: Union[str, Path]) -> bool:
- """
- Check if this parser can handle the given file.
-
- Args:
- file_path: Path to check
-
- Returns:
- True if file can be parsed
- """
- suffix = Path(file_path).suffix.lower()
- return suffix in cls.SUPPORTED_EXTENSIONS
diff --git a/deeptutor/services/rag/components/retrievers/__init__.py b/deeptutor/services/rag/components/retrievers/__init__.py
deleted file mode 100644
index a32e07db6..000000000
--- a/deeptutor/services/rag/components/retrievers/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-"""Document retrievers."""
-
-from .base import BaseRetriever
-from .dense import DenseRetriever
-
-__all__ = [
- "BaseRetriever",
- "DenseRetriever",
-]
diff --git a/deeptutor/services/rag/components/retrievers/base.py b/deeptutor/services/rag/components/retrievers/base.py
deleted file mode 100644
index c3f0cf7fc..000000000
--- a/deeptutor/services/rag/components/retrievers/base.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""
-Base Retriever
-==============
-
-Base class for document retrievers.
-"""
-
-from typing import Any, Dict
-
-from ..base import BaseComponent
-
-
-class BaseRetriever(BaseComponent):
- """
- Base class for document retrievers.
-
- Retrievers search indexed documents and return relevant results.
- """
-
- name = "base_retriever"
-
- async def process(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
- """
- Search for documents matching a query.
-
- Args:
- query: Search query
- kb_name: Knowledge base name
- **kwargs: Additional arguments
-
- Returns:
- Search results dictionary
- """
- raise NotImplementedError("Subclasses must implement process()")
diff --git a/deeptutor/services/rag/components/retrievers/dense.py b/deeptutor/services/rag/components/retrievers/dense.py
deleted file mode 100644
index 92a7354bc..000000000
--- a/deeptutor/services/rag/components/retrievers/dense.py
+++ /dev/null
@@ -1,211 +0,0 @@
-"""
-Dense Retriever
-===============
-
-Dense vector-based retriever using FAISS or cosine similarity.
-"""
-
-import json
-from pathlib import Path
-import pickle
-from typing import Any, Dict, Optional
-
-try:
- import numpy as np
-except ImportError: # pragma: no cover - optional dependency in minimal envs
- np = None
-
-from ..base import BaseComponent
-
-
-class DenseRetriever(BaseComponent):
- """
- Dense vector retriever.
-
- Uses FAISS for fast similarity search or falls back to
- cosine similarity if FAISS is unavailable.
- """
-
- name = "dense_retriever"
-
- def __init__(self, kb_base_dir: Optional[str] = None, top_k: int = 5):
- """
- Initialize dense retriever.
-
- Args:
- kb_base_dir: Base directory for knowledge bases
- top_k: Number of results to return
- """
- super().__init__()
- self.kb_base_dir = kb_base_dir or str(
- Path(__file__).resolve().parent.parent.parent.parent.parent.parent
- / "data"
- / "knowledge_bases"
- )
- self.top_k = top_k
-
- if np is None:
- self.logger.warning("NumPy not available, dense retriever is disabled")
- return
-
- # Try to import FAISS
- self.use_faiss = False
- try:
- import faiss
-
- self.faiss = faiss
- self.use_faiss = True
- except ImportError:
- self.logger.warning("FAISS not available, using simple cosine similarity")
-
- async def process(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
- """
- Search using dense embeddings with FAISS or cosine similarity.
-
- Args:
- query: Search query
- kb_name: Knowledge base name
- **kwargs: Additional arguments (mode, top_k, etc.)
-
- Returns:
- Search results dictionary with answer and sources
- """
- top_k = kwargs.get("top_k", self.top_k)
- self.logger.info(f"Dense search in {kb_name}: {query[:50]}... (top_k={top_k})")
-
- from deeptutor.services.embedding import get_embedding_client
-
- if np is None:
- self.logger.warning("NumPy not available, cannot run dense retrieval")
- return self._empty_response(query)
-
- # Get query embedding
- client = get_embedding_client()
- query_embedding = np.array((await client.embed([query]))[0], dtype=np.float32)
-
- # Load index
- kb_dir = Path(self.kb_base_dir) / kb_name / "vector_store"
- metadata_file = kb_dir / "metadata.json"
- info_file = kb_dir / "info.json"
-
- if not metadata_file.exists():
- self.logger.warning(f"No vector index found at {kb_dir}")
- return {
- "query": query,
- "answer": "No documents indexed. Please upload documents first.",
- "content": "",
- "mode": "dense",
- "provider": "llamaindex",
- "results": [],
- }
-
- # Load metadata and info (info.json is optional)
- with open(metadata_file, "r", encoding="utf-8") as f:
- metadata = json.load(f)
-
- if info_file.exists():
- with open(info_file, "r", encoding="utf-8") as f:
- info = json.load(f)
- else:
- info = {"use_faiss": False}
-
- use_faiss = info.get("use_faiss", False)
-
- if use_faiss and self.use_faiss:
- # Use FAISS for fast search
- index_file = kb_dir / "index.faiss"
- if not index_file.exists():
- self.logger.error(f"FAISS index file not found: {index_file}")
- return self._empty_response(query)
-
- # Load FAISS index
- index = self.faiss.read_index(str(index_file))
-
- # Normalize query vector for cosine similarity without modifying original
- norm = np.linalg.norm(query_embedding)
- if norm > 0:
- query_vec = (query_embedding / norm).reshape(1, -1)
- else:
- query_vec = query_embedding.reshape(1, -1)
-
- # Search
- distances, indices = index.search(query_vec, min(top_k, len(metadata)))
-
- # Build results
- results = []
- for dist, idx in zip(distances[0], indices[0]):
- if idx < len(metadata): # Valid index
- score = 1.0 / (1.0 + dist) # Convert distance to similarity score
- results.append((score, metadata[idx]))
- else:
- # Fallback: Load embeddings and use cosine similarity
- embeddings_file = kb_dir / "embeddings.pkl"
- if not embeddings_file.exists():
- self.logger.error(f"Embeddings file not found: {embeddings_file}")
- return self._empty_response(query)
-
- with open(embeddings_file, "rb") as f:
- embeddings = pickle.load(f)
-
- # Normalize for cosine similarity (avoid division by zero)
- query_norm = np.linalg.norm(query_embedding)
- if query_norm > 0:
- query_vec = query_embedding / query_norm
- else:
- query_vec = query_embedding # Keep as is if zero norm
-
- norms = np.linalg.norm(embeddings, axis=1, keepdims=True)
- # Replace zero norms with 1 to avoid division by zero
- norms = np.where(norms == 0, 1, norms)
- doc_vecs = embeddings / norms
-
- # Compute similarities
- similarities = np.dot(doc_vecs, query_vec)
-
- # Get top-k results
- top_indices = np.argsort(similarities)[::-1][:top_k]
-
- results = []
- for idx in top_indices:
- score = float(similarities[idx])
- results.append((score, metadata[idx]))
-
- # Build response content
- # Format chunks cleanly for LLM context (without score annotations)
- content_parts = []
- sources = []
- for score, item in results:
- content = item.get("content", "").strip()
- if content: # Only include non-empty chunks
- # Add chunk without score prefix for clean LLM input
- content_parts.append(content)
- sources.append(
- {
- "content": content,
- "score": score,
- "metadata": item.get("metadata", {}),
- }
- )
-
- # Join chunks with clear separation
- content = "\n\n".join(content_parts)
-
- return {
- "query": query,
- "answer": content, # Return clean context for LLM to use
- "content": content,
- "mode": "dense",
- "provider": "llamaindex",
- "results": sources,
- }
-
- def _empty_response(self, query: str) -> Dict[str, Any]:
- """Return empty response when no results found."""
- return {
- "query": query,
- "answer": "No relevant documents found.",
- "content": "",
- "mode": "dense",
- "provider": "llamaindex",
- "results": [],
- }
diff --git a/deeptutor/services/rag/factory.py b/deeptutor/services/rag/factory.py
index 7dc64cfd1..a49c37258 100644
--- a/deeptutor/services/rag/factory.py
+++ b/deeptutor/services/rag/factory.py
@@ -1,93 +1,55 @@
"""RAG pipeline factory.
-This module keeps a lightweight provider registry with a single built-in
-provider (`llamaindex`) while preserving the extension mechanism for future
-providers via `register_pipeline`.
+The project ships with a single LlamaIndex-backed pipeline. The helpers
+below remain because several call-sites import them; they have all been
+collapsed to operate on the single supported pipeline.
"""
from __future__ import annotations
-from typing import Callable, Dict, List, Optional
-import warnings
+from typing import Any, Dict, List, Optional
DEFAULT_PROVIDER = "llamaindex"
-LEGACY_PROVIDER_ALIASES = {
- "lightrag": DEFAULT_PROVIDER,
- "raganything": DEFAULT_PROVIDER,
- "raganything_docling": DEFAULT_PROVIDER,
-}
-# Pipeline registry - populated lazily
-_PIPELINES: Dict[str, Callable] = {}
-_PIPELINES_INITIALIZED = False
+# Cached pipeline instances keyed by kb_base_dir.
+_PIPELINE_CACHE: Dict[Optional[str], Any] = {}
-# Cached pipeline instances keyed by (name, kb_base_dir)
-_PIPELINE_CACHE: Dict[tuple[str, Optional[str]], object] = {}
+def normalize_provider_name(_name: Optional[str] = None) -> str:
+ """Always return the canonical provider name.
-def normalize_provider_name(name: Optional[str]) -> str:
- """Normalize provider names, folding legacy providers to llamaindex."""
- candidate = (name or DEFAULT_PROVIDER).strip().lower() or DEFAULT_PROVIDER
- return LEGACY_PROVIDER_ALIASES.get(candidate, candidate)
-
-
-def _init_pipelines() -> None:
- """Lazily initialize the built-in pipeline registry."""
- global _PIPELINES_INITIALIZED
- if _PIPELINES_INITIALIZED:
- return
-
- def _build_llamaindex(**kwargs):
- # Optional dependency: llama_index.
- from .pipelines.llamaindex import LlamaIndexPipeline
-
- return LlamaIndexPipeline(**kwargs)
-
- _PIPELINES.update(
- {
- DEFAULT_PROVIDER: _build_llamaindex,
- }
- )
- _PIPELINES_INITIALIZED = True
-
-
-def get_pipeline(name: str = DEFAULT_PROVIDER, kb_base_dir: Optional[str] = None, **kwargs):
- """Get a pipeline instance by name.
-
- Legacy provider names are normalized to `llamaindex` for backward
- compatibility with historical KB metadata/config.
+ Older configs/migrations may carry legacy provider strings (e.g.
+ ``lightrag``); they are all treated as the only supported pipeline.
"""
- _init_pipelines()
- normalized_name = normalize_provider_name(name)
- if normalized_name not in _PIPELINES:
- available = sorted(_PIPELINES.keys())
- raise ValueError(f"Unknown pipeline: {name}. Available: {available}")
+ return DEFAULT_PROVIDER
- if not kwargs:
- cache_key = (normalized_name, kb_base_dir)
- if cache_key in _PIPELINE_CACHE:
- return _PIPELINE_CACHE[cache_key]
- factory = _PIPELINES[normalized_name]
+def get_pipeline(
+ name: str = DEFAULT_PROVIDER,
+ kb_base_dir: Optional[str] = None,
+ **kwargs: Any,
+):
+ """Return the (cached) LlamaIndex pipeline instance.
- try:
- if kb_base_dir:
- kwargs["kb_base_dir"] = kb_base_dir
- instance = factory(**kwargs)
+ The ``name`` argument is accepted for backward compatibility but is
+ ignored — only the LlamaIndex pipeline is supported.
+ """
+ from .pipelines.llamaindex import LlamaIndexPipeline
- if not kwargs or (len(kwargs) == 1 and "kb_base_dir" in kwargs):
- _PIPELINE_CACHE[(normalized_name, kb_base_dir)] = instance
+ if kwargs:
+ # When custom kwargs are provided, build a fresh instance and skip
+ # the cache to honour overrides.
+ if kb_base_dir is not None:
+ kwargs.setdefault("kb_base_dir", kb_base_dir)
+ return LlamaIndexPipeline(**kwargs)
- return instance
- except ImportError as e:
- raise ValueError(
- f"Pipeline '{normalized_name}' is not available because an optional dependency "
- f"is missing: {e}. Please install llama-index dependencies."
- ) from e
+ if kb_base_dir not in _PIPELINE_CACHE:
+ _PIPELINE_CACHE[kb_base_dir] = LlamaIndexPipeline(kb_base_dir=kb_base_dir)
+ return _PIPELINE_CACHE[kb_base_dir]
def list_pipelines() -> List[Dict[str, str]]:
- """List available pipelines."""
+ """Return the single available pipeline (kept for callers that still ask)."""
return [
{
"id": DEFAULT_PROVIDER,
@@ -97,57 +59,9 @@ def list_pipelines() -> List[Dict[str, str]]:
]
-def register_pipeline(name: str, factory: Callable) -> None:
- """Register a custom pipeline factory."""
- _init_pipelines()
- normalized_name = name.strip().lower()
- _PIPELINES[normalized_name] = factory
-
-
-def has_pipeline(name: str) -> bool:
- """Check whether a pipeline exists.
-
- NOTE: this checks explicit registrations only. Legacy aliases are not treated
- as valid user-selectable providers.
- """
- _init_pipelines()
- candidate = (name or "").strip().lower()
- return candidate in _PIPELINES
-
-
-# Backward compatibility with old plugin API
-
-def get_plugin(name: str) -> Dict[str, Callable]:
- """DEPRECATED: Use get_pipeline() instead."""
- warnings.warn(
- "get_plugin() is deprecated, use get_pipeline() instead",
- DeprecationWarning,
- stacklevel=2,
- )
-
- pipeline = get_pipeline(name)
- return {
- "initialize": pipeline.initialize,
- "search": pipeline.search,
- "delete": getattr(pipeline, "delete", lambda kb: True),
- }
-
-
-def list_plugins() -> List[Dict[str, str]]:
- """DEPRECATED: Use list_pipelines() instead."""
- warnings.warn(
- "list_plugins() is deprecated, use list_pipelines() instead",
- DeprecationWarning,
- stacklevel=2,
- )
- return list_pipelines()
-
-
-def has_plugin(name: str) -> bool:
- """DEPRECATED: Use has_pipeline() instead."""
- warnings.warn(
- "has_plugin() is deprecated, use has_pipeline() instead",
- DeprecationWarning,
- stacklevel=2,
- )
- return has_pipeline(name)
+__all__ = [
+ "DEFAULT_PROVIDER",
+ "get_pipeline",
+ "list_pipelines",
+ "normalize_provider_name",
+]
diff --git a/deeptutor/services/rag/components/routing.py b/deeptutor/services/rag/file_routing.py
similarity index 53%
rename from deeptutor/services/rag/components/routing.py
rename to deeptutor/services/rag/file_routing.py
index 024770c61..8cca4cb5e 100644
--- a/deeptutor/services/rag/components/routing.py
+++ b/deeptutor/services/rag/file_routing.py
@@ -2,7 +2,7 @@
File Type Router
================
-Centralized file type classification and routing for RAG pipelines.
+Centralized file type classification and routing for the RAG pipeline.
Determines the appropriate processing method for each document type.
"""
@@ -17,80 +17,53 @@ logger = get_logger("FileTypeRouter")
class DocumentType(Enum):
- """Document type classification"""
+ """Document type classification."""
- PDF = "pdf" # Requires PDF parser
- TEXT = "text" # Plain text, direct read
- MARKDOWN = "markdown" # Structured text
- DOCX = "docx" # Word documents
- IMAGE = "image" # Images (may need OCR)
- UNKNOWN = "unknown" # Unsupported
+ PDF = "pdf"
+ TEXT = "text"
+ MARKDOWN = "markdown"
+ DOCX = "docx"
+ IMAGE = "image"
+ UNKNOWN = "unknown"
@dataclass
class FileClassification:
- """
- Result of file classification.
-
- Attributes:
- parser_files: Files requiring parser processing (currently PDF)
- text_files: Files that can be read directly as text
- unsupported: Files with unsupported formats
- """
+ """Result of file classification."""
parser_files: List[str]
text_files: List[str]
unsupported: List[str]
+
class FileTypeRouter:
- """
- File type router for RAG pipelines.
+ """File type router for the RAG pipeline.
Classifies files before processing to route them to appropriate handlers:
- PDF files -> PDF parsing
- Text files -> Direct read (fast, simple)
- Unsupported -> Skip with warning
-
- Usage:
- router = FileTypeRouter()
- classification = router.classify_files(file_paths)
-
- # Process PDF files with parser
- for pdf in classification.parser_files:
- ...
-
- # Process text files directly
- for txt in classification.text_files:
- content = await FileTypeRouter.read_text_file(txt)
- ...
"""
- # Extensions requiring parser processing (currently PDF)
PARSER_EXTENSIONS = {".pdf"}
- # Extensions for direct text reading
TEXT_EXTENSIONS = {
- # Plain text
".txt",
".text",
".log",
- # Markup languages
".md",
".markdown",
".rst",
".asciidoc",
- # Data formats
".json",
".yaml",
".yml",
".toml",
".csv",
".tsv",
- # LaTeX
".tex",
".latex",
".bib",
- # Code files
".py",
".js",
".ts",
@@ -114,7 +87,6 @@ class FileTypeRouter:
".bash",
".zsh",
".ps1",
- # Web
".html",
".htm",
".xml",
@@ -122,7 +94,6 @@ class FileTypeRouter:
".scss",
".sass",
".less",
- # Config
".ini",
".cfg",
".conf",
@@ -130,23 +101,12 @@ class FileTypeRouter:
".properties",
}
- # Word document extensions (unsupported in llamaindex-only mode)
DOCX_EXTENSIONS = {".docx", ".doc"}
-
- # Image extensions (unsupported in llamaindex-only mode)
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif"}
@classmethod
def get_document_type(cls, file_path: str) -> DocumentType:
- """
- Classify a single file by its type.
-
- Args:
- file_path: Path to the file
-
- Returns:
- DocumentType enum value
- """
+ """Classify a single file by its type."""
ext = Path(file_path).suffix.lower()
if ext in cls.PARSER_EXTENSIONS:
@@ -158,32 +118,20 @@ class FileTypeRouter:
elif ext in cls.IMAGE_EXTENSIONS:
return DocumentType.IMAGE
else:
- # Try to detect if it's a text file by content
if cls._is_text_file(file_path):
return DocumentType.TEXT
return DocumentType.UNKNOWN
@classmethod
def _is_text_file(cls, file_path: str, sample_size: int = 8192) -> bool:
- """
- Detect if a file is text-based by examining its content.
-
- Args:
- file_path: Path to the file
- sample_size: Number of bytes to sample
-
- Returns:
- True if file appears to be text
- """
+ """Detect if a file is text-based by examining its content."""
try:
with open(file_path, "rb") as f:
chunk = f.read(sample_size)
- # Check for null bytes (binary file indicator)
if b"\x00" in chunk:
return False
- # Try to decode as UTF-8
chunk.decode("utf-8")
return True
except (UnicodeDecodeError, IOError, OSError):
@@ -191,15 +139,7 @@ class FileTypeRouter:
@classmethod
def classify_files(cls, file_paths: List[str]) -> FileClassification:
- """
- Classify a list of files by processing method.
-
- Args:
- file_paths: List of file paths to classify
-
- Returns:
- FileClassification with files grouped by processing method
- """
+ """Classify a list of files by processing method."""
parser_files = []
text_files = []
unsupported = []
@@ -227,15 +167,7 @@ class FileTypeRouter:
@classmethod
async def read_text_file(cls, file_path: str) -> str:
- """
- Read a text file with automatic encoding detection.
-
- Args:
- file_path: Path to the text file
-
- Returns:
- File content as string
- """
+ """Read a text file with automatic encoding detection."""
encodings = ["utf-8", "utf-8-sig", "gbk", "gb2312", "gb18030", "latin-1", "cp1252"]
for encoding in encodings:
@@ -245,64 +177,27 @@ class FileTypeRouter:
except UnicodeDecodeError:
continue
- # Last resort: read with error replacement
with open(file_path, "rb") as f:
return f.read().decode("utf-8", errors="replace")
@classmethod
def needs_parser(cls, file_path: str) -> bool:
- """
- Quick check if a single file needs parser processing.
-
- Args:
- file_path: Path to the file
-
- Returns:
- True if file requires parser processing
- """
+ """Quick check if a single file needs parser processing."""
doc_type = cls.get_document_type(file_path)
return doc_type in (DocumentType.PDF, DocumentType.DOCX, DocumentType.IMAGE)
@classmethod
def is_text_readable(cls, file_path: str) -> bool:
- """
- Check if a file can be read directly as text.
-
- Args:
- file_path: Path to the file
-
- Returns:
- True if file can be read as text
- """
+ """Check if a file can be read directly as text."""
doc_type = cls.get_document_type(file_path)
return doc_type in (DocumentType.TEXT, DocumentType.MARKDOWN)
@classmethod
- def get_extensions_for_provider(cls, provider: str) -> set[str]:
- """
- Get supported file extensions for a specific RAG provider.
-
- Args:
- provider: RAG provider name
-
- Returns:
- Set of supported file extensions (with leading dot, e.g., {".pdf", ".txt"})
- """
- # Only llamaindex is supported; keep provider param for forward compatibility.
- if provider and provider != "llamaindex":
- logger.warning(f"Unknown/legacy provider '{provider}', using llamaindex extension set")
+ def get_supported_extensions(cls) -> set[str]:
+ """Get the set of all supported file extensions."""
return cls.PARSER_EXTENSIONS | cls.TEXT_EXTENSIONS
@classmethod
- def get_glob_patterns_for_provider(cls, provider: str) -> list[str]:
- """
- Get glob patterns for file searching based on RAG provider.
-
- Args:
- provider: RAG provider name
-
- Returns:
- List of glob patterns (e.g., ["*.pdf", "*.txt", "*.md"])
- """
- extensions = cls.get_extensions_for_provider(provider)
- return [f"*{ext}" for ext in sorted(extensions)]
+ def get_glob_patterns(cls) -> list[str]:
+ """Get glob patterns for file searching."""
+ return [f"*{ext}" for ext in sorted(cls.get_supported_extensions())]
diff --git a/deeptutor/services/rag/parsers/__init__.py b/deeptutor/services/rag/parsers/__init__.py
deleted file mode 100644
index 04d4261fc..000000000
--- a/deeptutor/services/rag/parsers/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-"""RAG parser integrations.
-
-No external parser integrations are bundled in llamaindex-only mode.
-"""
-
-__all__: list[str] = []
diff --git a/deeptutor/services/rag/pipeline.py b/deeptutor/services/rag/pipeline.py
deleted file mode 100644
index 20dcf4710..000000000
--- a/deeptutor/services/rag/pipeline.py
+++ /dev/null
@@ -1,215 +0,0 @@
-"""
-RAG Pipeline
-============
-
-Composable RAG pipeline with fluent API.
-"""
-
-import asyncio
-from pathlib import Path
-import shutil
-from typing import Any, Dict, List, Optional
-
-from deeptutor.logging import get_logger
-
-from .components.base import Component
-from .components.routing import FileTypeRouter
-from .types import Document
-
-# Default knowledge base directory
-DEFAULT_KB_BASE_DIR = str(
- Path(__file__).resolve().parent.parent.parent.parent / "data" / "knowledge_bases"
-)
-
-
-class RAGPipeline:
- """
- Composable RAG pipeline.
-
- Build custom RAG pipelines using a fluent API:
-
- pipeline = (
- RAGPipeline("custom", kb_base_dir="/path/to/kb")
- .parser(PDFParser())
- .chunker(SemanticChunker())
- .embedder(OpenAIEmbedder())
- .indexer(VectorIndexer())
- .retriever(DenseRetriever())
- )
-
- await pipeline.initialize("kb_name", ["doc1.pdf"])
- result = await pipeline.search("query", "kb_name")
- """
-
- def __init__(self, name: str = "default", kb_base_dir: Optional[str] = None):
- """
- Initialize RAG pipeline.
-
- Args:
- name: Pipeline name for logging
- kb_base_dir: Base directory for knowledge bases
- """
- self.name = name
- self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIR
- self.logger = get_logger(f"Pipeline:{name}")
- self._parser: Optional[Component] = None
- self._chunkers: List[Component] = []
- self._embedder: Optional[Component] = None
- self._indexers: List[Component] = []
- self._retriever: Optional[Component] = None
-
- # Fluent API methods
- def parser(self, p: Component) -> "RAGPipeline":
- """Set the document parser."""
- self._parser = p
- return self
-
- def chunker(self, c: Component) -> "RAGPipeline":
- """Add a chunker to the pipeline."""
- self._chunkers.append(c)
- return self
-
- def embedder(self, e: Component) -> "RAGPipeline":
- """Set the embedder."""
- self._embedder = e
- return self
-
- def indexer(self, i: Component) -> "RAGPipeline":
- """Add an indexer to the pipeline."""
- self._indexers.append(i)
- return self
-
- def retriever(self, r: Component) -> "RAGPipeline":
- """Set the retriever."""
- self._retriever = r
- return self
-
- async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
- """
- Run full initialization pipeline.
-
- Uses FileTypeRouter to classify files and route them appropriately:
- - PDF/complex files -> configured parser (e.g., PDFParser)
- - Text files -> direct text reading (fast path)
-
- Args:
- kb_name: Knowledge base name
- file_paths: List of file paths to process
- **kwargs: Additional arguments passed to components
-
- Returns:
- True if successful
- """
- self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files")
-
- if not self._parser:
- raise ValueError("No parser configured. Use .parser() to set one")
-
- # Stage 1: Parse documents with file type routing
- self.logger.info("Stage 1: Parsing documents...")
-
- # Classify files by type
- classification = FileTypeRouter.classify_files(file_paths)
- self.logger.info(
- f"File classification: {len(classification.parser_files)} parser, "
- f"{len(classification.text_files)} text, "
- f"{len(classification.unsupported)} unsupported"
- )
-
- documents = []
-
- # Process complex files (PDF, etc.) with configured parser
- for path in classification.parser_files:
- self.logger.info(f"Parsing (parser): {Path(path).name}")
- doc = await self._parser.process(path, **kwargs)
- documents.append(doc)
-
- # Process text files directly (fast path)
- for path in classification.text_files:
- self.logger.info(f"Parsing (direct text): {Path(path).name}")
- content = await FileTypeRouter.read_text_file(path)
- doc = Document(
- content=content,
- file_path=str(path),
- metadata={
- "filename": Path(path).name,
- "parser": "direct_text",
- },
- )
- documents.append(doc)
-
- # Log unsupported files
- for path in classification.unsupported:
- self.logger.warning(f"Skipped unsupported file: {Path(path).name}")
-
- # Stage 2: Chunk (sequential - later chunkers see earlier results)
- if self._chunkers:
- self.logger.info("Stage 2: Chunking...")
- for chunker in self._chunkers:
- for doc in documents:
- new_chunks = await chunker.process(doc, **kwargs)
- doc.chunks.extend(new_chunks)
-
- # Stage 3: Embed
- if self._embedder:
- self.logger.info("Stage 3: Embedding...")
- for doc in documents:
- await self._embedder.process(doc, **kwargs)
-
- # Stage 4: Index (can run in parallel)
- if self._indexers:
- self.logger.info("Stage 4: Indexing...")
- await asyncio.gather(
- *[indexer.process(kb_name, documents, **kwargs) for indexer in self._indexers]
- )
-
- self.logger.info(f"KB '{kb_name}' initialized successfully")
- return True
-
- async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
- """
- Search the knowledge base.
-
- Args:
- query: Search query
- kb_name: Knowledge base name
- **kwargs: Additional arguments passed to retriever
-
- Returns:
- Search results dictionary
- """
- if not self._retriever:
- raise ValueError("No retriever configured. Use .retriever() to set one")
-
- return await self._retriever.process(query, kb_name=kb_name, **kwargs)
-
- async def delete(self, kb_name: str) -> bool:
- """
- Delete a knowledge base.
-
- Args:
- kb_name: Knowledge base name
-
- Returns:
- True if successful
- """
- # Validate kb_name to prevent path traversal
- if not kb_name or kb_name in (".", "..") or "/" in kb_name or "\\" in kb_name:
- raise ValueError(f"Invalid knowledge base name: {kb_name}")
-
- self.logger.info(f"Deleting KB '{kb_name}'")
-
- kb_dir = Path(self.kb_base_dir) / kb_name
- # Ensure the resolved path is within the base directory
- kb_dir = kb_dir.resolve()
- base_dir = Path(self.kb_base_dir).resolve()
- if not kb_dir.is_relative_to(base_dir):
- raise ValueError(f"Knowledge base path outside allowed directory: {kb_name}")
-
- if kb_dir.exists():
- shutil.rmtree(kb_dir)
- self.logger.info(f"Deleted KB directory: {kb_dir}")
- return True
-
- self.logger.warning(f"KB directory not found: {kb_dir}")
- return False
diff --git a/deeptutor/services/rag/pipelines/llamaindex.py b/deeptutor/services/rag/pipelines/llamaindex.py
index 5e2b4577f..7572088a0 100644
--- a/deeptutor/services/rag/pipelines/llamaindex.py
+++ b/deeptutor/services/rag/pipelines/llamaindex.py
@@ -21,7 +21,7 @@ from llama_index.core.bridge.pydantic import PrivateAttr
from deeptutor.logging import get_logger
from deeptutor.services.embedding import get_embedding_client, get_embedding_config
-from deeptutor.services.rag.components.routing import FileTypeRouter
+from deeptutor.services.rag.file_routing import FileTypeRouter
# Default knowledge base directory
DEFAULT_KB_BASE_DIR = str(
diff --git a/deeptutor/services/rag/service.py b/deeptutor/services/rag/service.py
index 8c6251ae9..3f87fbac2 100644
--- a/deeptutor/services/rag/service.py
+++ b/deeptutor/services/rag/service.py
@@ -10,13 +10,7 @@ from typing import Any, Dict, List, Optional
from deeptutor.logging import get_logger
-from .factory import (
- DEFAULT_PROVIDER,
- get_pipeline,
- has_pipeline,
- list_pipelines,
- normalize_provider_name,
-)
+from .factory import DEFAULT_PROVIDER, get_pipeline, list_pipelines
class _RAGRawLogHandler(logging.Handler):
@@ -59,35 +53,27 @@ DEFAULT_KB_BASE_DIR = str(
class RAGService:
- """Unified RAG service that currently uses llamaindex provider(s)."""
+ """Unified RAG service backed by the LlamaIndex pipeline."""
def __init__(
self,
kb_base_dir: Optional[str] = None,
- provider: Optional[str] = None,
+ provider: Optional[str] = None, # accepted for backward compatibility
):
self.logger = get_logger("RAGService")
self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIR
- from deeptutor.services.config import get_kb_config_service
-
- configured_default = (
- get_kb_config_service()
- .get_all_configs()
- .get("defaults", {})
- .get("rag_provider", DEFAULT_PROVIDER)
- )
- self.provider = normalize_provider_name(provider or configured_default)
+ self.provider = DEFAULT_PROVIDER
self._pipeline = None
def _get_pipeline(self):
if self._pipeline is None:
- self._pipeline = get_pipeline(self.provider, kb_base_dir=self.kb_base_dir)
+ self._pipeline = get_pipeline(kb_base_dir=self.kb_base_dir)
return self._pipeline
async def initialize(
self, kb_name: str, file_paths: List[str], **kwargs
) -> bool:
- self.logger.info(f"Initializing KB '{kb_name}' with provider '{self.provider}'")
+ self.logger.info(f"Initializing KB '{kb_name}'")
pipeline = self._get_pipeline()
return await pipeline.initialize(
kb_name=kb_name, file_paths=file_paths, **kwargs
@@ -101,31 +87,24 @@ class RAGService:
**kwargs,
) -> Dict[str, Any]:
kwargs.pop("mode", None)
- provider = self._get_provider_for_kb(kb_name)
- with self._capture_raw_logs(event_sink, provider):
+ with self._capture_raw_logs(event_sink):
await self._emit_tool_event(
event_sink,
"status",
f"Query: {query}",
{"query": query, "kb_name": kb_name, "trace_layer": "summary"},
)
- await self._emit_tool_event(
- event_sink,
- "status",
- f"Selecting provider: {provider}",
- {"provider": provider, "trace_layer": "summary"},
- )
self.logger.info(
- f"Searching KB '{kb_name}' with provider '{provider}' and query: {query[:50]}..."
+ f"Searching KB '{kb_name}' with query: {query[:50]}..."
)
- pipeline = get_pipeline(provider, kb_base_dir=self.kb_base_dir)
+ pipeline = self._get_pipeline()
await self._emit_tool_event(
event_sink,
"status",
f"Retrieving from knowledge base '{kb_name}'...",
- {"provider": provider, "trace_layer": "summary"},
+ {"provider": DEFAULT_PROVIDER, "trace_layer": "summary"},
)
result = await pipeline.search(query=query, kb_name=kb_name, **kwargs)
@@ -136,7 +115,7 @@ class RAGService:
result["answer"] = result["content"]
if "content" not in result and "answer" in result:
result["content"] = result["answer"]
- result["provider"] = normalize_provider_name(result.get("provider") or provider)
+ result["provider"] = DEFAULT_PROVIDER
answer = result.get("answer") or result.get("content") or ""
await self._emit_tool_event(
@@ -144,7 +123,7 @@ class RAGService:
"status",
f"Retrieved {len(answer)} characters of grounded context.",
{
- "provider": result["provider"],
+ "provider": DEFAULT_PROVIDER,
"kb_name": kb_name,
"trace_layer": "summary",
},
@@ -163,7 +142,7 @@ class RAGService:
return
await event_sink(event_type, message, metadata or {})
- def _capture_raw_logs(self, event_sink, provider: str):
+ def _capture_raw_logs(self, event_sink):
from contextlib import ExitStack, contextmanager
import asyncio
@@ -176,7 +155,14 @@ class RAGService:
loop = asyncio.get_running_loop()
handler = _RAGRawLogHandler(event_sink, loop)
handler.setLevel(logging.DEBUG)
- targets = self._iter_rag_loggers(provider)
+ targets = [
+ logging.getLogger(name)
+ for name in (
+ "deeptutor.RAGService",
+ "deeptutor.RAGForward",
+ "deeptutor.LlamaIndexPipeline",
+ )
+ ]
with ExitStack() as stack:
for logger in targets:
logger.addHandler(handler)
@@ -188,34 +174,6 @@ class RAGService:
return _manager()
- def _iter_rag_loggers(self, provider: str) -> list[logging.Logger]:
- provider_name = normalize_provider_name(provider)
- names = {
- "deeptutor.RAGService",
- "deeptutor.RAGForward",
- }
- if provider_name == DEFAULT_PROVIDER:
- names.add("deeptutor.LlamaIndexPipeline")
- return [logging.getLogger(name) for name in sorted(names)]
-
- def _get_provider_for_kb(self, kb_name: str) -> str:
- """Resolve provider from KB config and normalize legacy values."""
- try:
- from deeptutor.services.config import get_kb_config_service
-
- service = get_kb_config_service()
- provider_raw = service.get_kb_config(kb_name).get("rag_provider")
- provider = normalize_provider_name(provider_raw)
- if provider_raw and provider_raw != provider:
- service.set_rag_provider(kb_name, provider)
- self.logger.info(
- f"Normalized legacy provider '{provider_raw}' -> '{provider}' for KB '{kb_name}'"
- )
- return provider
- except Exception as e:
- self.logger.warning(f"Error reading provider from config: {e}, using instance provider")
- return self.provider
-
async def delete(self, kb_name: str) -> bool:
self.logger.info(f"Deleting KB '{kb_name}'")
pipeline = self._get_pipeline()
@@ -296,8 +254,11 @@ class RAGService:
@staticmethod
def get_current_provider() -> str:
- return normalize_provider_name(os.getenv("RAG_PROVIDER", DEFAULT_PROVIDER))
+ # ``RAG_PROVIDER`` env var is honoured for visibility but the
+ # service only ships with a single backend.
+ os.getenv("RAG_PROVIDER")
+ return DEFAULT_PROVIDER
@staticmethod
def has_provider(name: str) -> bool:
- return has_pipeline((name or "").strip().lower())
+ return (name or "").strip().lower() == DEFAULT_PROVIDER
diff --git a/deeptutor/services/rag/types.py b/deeptutor/services/rag/types.py
deleted file mode 100644
index 3ea597159..000000000
--- a/deeptutor/services/rag/types.py
+++ /dev/null
@@ -1,73 +0,0 @@
-"""
-RAG Types
-=========
-
-Data types for the RAG pipeline.
-"""
-
-from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
-
-
-@dataclass
-class Chunk:
- """
- Document chunk.
-
- Represents a portion of a document with optional metadata and embedding.
- """
-
- content: str
- chunk_type: str = "text" # text, definition, theorem, equation, figure, table...
- metadata: Dict[str, Any] = field(default_factory=dict)
- embedding: Optional[List[float]] = None
-
- def __post_init__(self):
- if self.metadata is None:
- self.metadata = {}
-
-
-@dataclass
-class Document:
- """
- Parsed document.
-
- Contains the full document content, metadata, and chunks.
- """
-
- content: str
- file_path: str = ""
- metadata: Dict[str, Any] = field(default_factory=dict)
- chunks: List[Chunk] = field(default_factory=list)
- content_items: List[Dict] = field(default_factory=list) # Parsed content-item format
-
- def __post_init__(self):
- if self.metadata is None:
- self.metadata = {}
- if self.chunks is None:
- self.chunks = []
- if self.content_items is None:
- self.content_items = []
-
- def add_chunk(self, chunk: Chunk):
- """Add a chunk to the document."""
- self.chunks.append(chunk)
-
- def get_chunks_by_type(self, chunk_type: str) -> List[Chunk]:
- """Get all chunks of a specific type."""
- return [c for c in self.chunks if c.chunk_type == chunk_type]
-
-
-@dataclass
-class SearchResult:
- """
- Search result from RAG query.
- """
-
- query: str
- answer: str
- content: str
- mode: str = "hybrid"
- provider: str = "llamaindex"
- chunks: List[Chunk] = field(default_factory=list)
- metadata: Dict[str, Any] = field(default_factory=dict)
diff --git a/deeptutor/services/rag/utils/__init__.py b/deeptutor/services/rag/utils/__init__.py
deleted file mode 100644
index f5f909168..000000000
--- a/deeptutor/services/rag/utils/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-"""RAG utility helpers.
-
-No standalone utility exports are required in llamaindex-only mode.
-"""
-
-__all__: list[str] = []
diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.py
index 7feecc8ce..2713185b5 100644
--- a/deeptutor/services/setup/init.py
+++ b/deeptutor/services/setup/init.py
@@ -54,7 +54,6 @@ DEFAULT_MAIN_SETTINGS = {
},
"capabilities": {
"question": {
- "rag_query_count": 3,
"max_parallel_questions": 1,
"idea_loop": {"max_rounds": 3, "ideas_per_round": 5},
"generation": {"max_retries": 2},
@@ -75,7 +74,6 @@ DEFAULT_MAIN_SETTINGS = {
"tool_max_retries": 2,
"paper_search_years_limit": 3,
},
- "rag": {},
},
},
}
diff --git a/deeptutor/services/tutorbot/manager.py b/deeptutor/services/tutorbot/manager.py
index 97ad46300..8fdc18603 100644
--- a/deeptutor/services/tutorbot/manager.py
+++ b/deeptutor/services/tutorbot/manager.py
@@ -10,13 +10,13 @@ Memory is shared across all bots via ``data/memory/``.
from __future__ import annotations
import asyncio
-import logging
-import shutil
-import sys
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from datetime import datetime
+import logging
from pathlib import Path
+import shutil
+import sys
from typing import Any
import yaml
@@ -31,6 +31,57 @@ _BUILTIN_TEMPLATES_DIR = _PACKAGE_TUTORBOT / "templates"
_RESERVED_NAMES = {"workspace", "media", "cron", "logs", "sessions", "_souls"}
+# Substrings (case-insensitive) on channel field names that flag a value as a
+# secret which must be masked before being serialised in non-edit responses.
+# Matches existing channel configs: telegram.token, slack.bot_token /
+# slack.app_token, discord.token, matrix.access_token, whatsapp.bridge_token,
+# mochat.claw_token, feishu.app_secret / encrypt_key / verification_token,
+# wecom.secret, qq.secret, dingtalk.client_secret, email.imap_password /
+# smtp_password, etc.
+_SECRET_FIELD_HINTS: tuple[str, ...] = (
+ "token",
+ "secret",
+ "password",
+ "api_key",
+ "apikey",
+ "encrypt_key",
+)
+_SECRET_MASK = "***"
+
+
+def _is_secret_field(name: str) -> bool:
+ n = name.lower()
+ return any(hint in n for hint in _SECRET_FIELD_HINTS)
+
+
+def mask_channel_secrets(channels: dict[str, Any]) -> dict[str, Any]:
+ """Deep-copy ``channels`` and replace any secret-looking string field with ``***``.
+
+ Lists/tuples are walked element-wise; non-string secret values are passed
+ through unchanged so we don't accidentally hide non-credential booleans
+ (e.g. a ``token_required`` flag, hypothetical).
+ """
+ def _walk(value: Any, key_hint: str | None = None) -> Any:
+ if isinstance(value, dict):
+ return {k: _walk(v, key_hint=k) for k, v in value.items()}
+ if isinstance(value, list):
+ return [_walk(v, key_hint=key_hint) for v in value]
+ if isinstance(value, tuple):
+ return tuple(_walk(v, key_hint=key_hint) for v in value)
+ if (
+ key_hint is not None
+ and _is_secret_field(key_hint)
+ and isinstance(value, str)
+ and value
+ ):
+ return _SECRET_MASK
+ return value
+
+ walked = _walk(channels)
+ if not isinstance(walked, dict): # defensive — should not happen
+ return {}
+ return walked
+
@dataclass
class BotConfig:
@@ -56,21 +107,50 @@ class TutorBotInstance:
heartbeat: Any = None
notify_queue: asyncio.Queue = field(default_factory=asyncio.Queue)
channel_bindings: dict[str, str] = field(default_factory=dict)
+ # Serialise concurrent reload_channels invocations on the same bot.
+ reload_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
+ # Last error from reload_channels (clears on success); surfaced via API
+ # so the UI can warn that on-disk config and live listeners diverged.
+ last_reload_error: str | None = None
@property
def running(self) -> bool:
return any(not t.done() for t in self.tasks)
- def to_dict(self) -> dict[str, Any]:
+ def to_dict(
+ self,
+ *,
+ include_secrets: bool = False,
+ mask_secrets: bool = False,
+ ) -> dict[str, Any]:
+ """Serialise instance to a JSON-friendly dict.
+
+ Channel field shape:
+ - default (``include_secrets=False, mask_secrets=False``): list of channel
+ names — safe for list / index endpoints.
+ - ``mask_secrets=True``: full nested dict, but secret-looking strings
+ replaced with ``***`` — safe for read-only detail views.
+ - ``include_secrets=True``: full nested dict including raw secrets —
+ ONLY use for the admin edit form (and only on the explicitly-opt-in
+ single-bot GET).
+ """
+ if include_secrets:
+ channels: Any = self.config.channels
+ elif mask_secrets:
+ channels = mask_channel_secrets(self.config.channels)
+ else:
+ channels = list(self.config.channels.keys())
+
return {
"bot_id": self.bot_id,
"name": self.config.name,
"description": self.config.description,
"persona": self.config.persona,
- "channels": self.config.channels,
+ "channels": channels,
"model": self.config.model,
"running": self.running,
"started_at": self.started_at.isoformat(),
+ "last_reload_error": self.last_reload_error,
}
@@ -261,10 +341,10 @@ class TutorBotManager:
config = BotConfig(name=bot_id)
self.save_bot_config(bot_id, config)
- from deeptutor.tutorbot.providers.deeptutor_adapter import create_deeptutor_provider
- from deeptutor.tutorbot.bus.queue import MessageBus
from deeptutor.tutorbot.agent.loop import AgentLoop
+ from deeptutor.tutorbot.bus.queue import MessageBus
from deeptutor.tutorbot.config.schema import ExecToolConfig
+ from deeptutor.tutorbot.providers.deeptutor_adapter import create_deeptutor_provider
from deeptutor.tutorbot.session.manager import SessionManager
provider = create_deeptutor_provider()
@@ -295,25 +375,11 @@ class TutorBotManager:
)
# -- Channel setup ---------------------------------------------------
- channel_manager = None
- if config.channels:
- try:
- from deeptutor.tutorbot.channels.manager import ChannelManager
- from deeptutor.tutorbot.config.schema import ChannelsConfig
-
- channels_config = ChannelsConfig(**config.channels)
- channel_manager = ChannelManager(channels_config, bus)
- if channel_manager.channels:
- logger.info(
- "Channels enabled for bot '%s': %s",
- bot_id, list(channel_manager.channels.keys()),
- )
- else:
- logger.info("No channels matched config for bot '%s'", bot_id)
- channel_manager = None
- except Exception:
- logger.exception("Failed to initialise channels for bot '%s'", bot_id)
- channel_manager = None
+ try:
+ channel_manager = self._build_channel_manager(config, bus, bot_id=bot_id)
+ except Exception:
+ logger.exception("Failed to initialise channels for bot '%s'", bot_id)
+ channel_manager = None
instance = TutorBotInstance(
bot_id=bot_id,
@@ -453,15 +519,86 @@ class TutorBotManager:
logger.info("TutorBot '%s' stopped", bot_id)
return True
+ def _build_channel_manager(
+ self,
+ config: BotConfig,
+ bus: Any,
+ *,
+ bot_id: str,
+ ) -> Any | None:
+ """Construct a ``ChannelManager`` from ``config.channels`` or return ``None``.
+
+ Centralised so ``start_bot`` and ``reload_channels`` produce identical
+ behaviour. Raises ``pydantic.ValidationError`` if the channels dict is
+ malformed; callers decide whether to swallow or propagate.
+ """
+ if not config.channels:
+ return None
+ from deeptutor.tutorbot.channels.manager import ChannelManager
+ from deeptutor.tutorbot.config.schema import ChannelsConfig
+
+ channels_config = ChannelsConfig(**config.channels)
+ manager = ChannelManager(channels_config, bus)
+ if not manager.channels:
+ logger.info("No channels matched config for bot '%s'", bot_id)
+ return None
+ logger.info(
+ "Channels enabled for bot '%s': %s",
+ bot_id, list(manager.channels.keys()),
+ )
+ return manager
+
async def reload_channels(self, bot_id: str) -> None:
"""Restart channel listeners from ``instance.config.channels`` (same MessageBus).
- Cancels only ``tutorbot:{bot_id}:ch:*`` tasks; agent loop and outbound router keep running.
+ Cancels only ``tutorbot:{bot_id}:ch:*`` tasks; agent loop and outbound
+ router keep running. Concurrent invocations on the same bot are
+ serialised via ``instance.reload_lock`` to avoid duplicate listeners.
+
+ On success, ``instance.last_reload_error`` is cleared. On failure, the
+ listeners are torn down (bot is left running with no channels) and the
+ error is recorded; callers should surface it to the user.
"""
instance = self._bots.get(bot_id)
if not instance or not instance.running:
return
+ async with instance.reload_lock:
+ await self._teardown_channel_listeners(instance, bot_id)
+
+ try:
+ channel_manager = self._build_channel_manager(
+ instance.config, instance.agent_loop.bus, bot_id=bot_id,
+ )
+ except Exception as exc:
+ logger.exception("Failed to reload channels for bot '%s'", bot_id)
+ instance.channel_manager = None
+ instance.last_reload_error = f"{type(exc).__name__}: {exc}"
+ raise
+
+ instance.channel_manager = channel_manager
+ instance.last_reload_error = None
+ if channel_manager:
+ for ch_name, ch in channel_manager.channels.items():
+ ch_task = asyncio.create_task(
+ ch.start(), name=f"tutorbot:{bot_id}:ch:{ch_name}",
+ )
+ instance.tasks.append(ch_task)
+ logger.info(
+ "Reloaded channels for bot '%s': %s",
+ bot_id, list(channel_manager.channels.keys()),
+ )
+
+ async def _teardown_channel_listeners(
+ self, instance: TutorBotInstance, bot_id: str,
+ ) -> None:
+ """Cancel ``tutorbot:{bot_id}:ch:*`` tasks and stop the existing manager.
+
+ Note: ``channel_bindings`` are intentionally cleared — they map
+ channel→last-seen chat_id and will be rebuilt as the rebooted listeners
+ receive new traffic. Pending heartbeat replies bound to a stale chat_id
+ will be dropped (acceptable: same behaviour as Stop/Start).
+ """
ch_prefix = f"tutorbot:{bot_id}:ch:"
to_remove = [t for t in instance.tasks if (t.get_name() or "").startswith(ch_prefix)]
for t in to_remove:
@@ -483,34 +620,6 @@ class TutorBotManager:
instance.channel_manager = None
instance.channel_bindings.clear()
- bus = instance.agent_loop.bus
- config = instance.config
- channel_manager = None
- if config.channels:
- try:
- from deeptutor.tutorbot.channels.manager import ChannelManager
- from deeptutor.tutorbot.config.schema import ChannelsConfig
-
- channels_config = ChannelsConfig(**config.channels)
- channel_manager = ChannelManager(channels_config, bus)
- if not channel_manager.channels:
- channel_manager = None
- except Exception:
- logger.exception("Failed to reload channels for bot '%s'", bot_id)
- raise
-
- instance.channel_manager = channel_manager
- if channel_manager:
- for ch_name, ch in channel_manager.channels.items():
- ch_task = asyncio.create_task(
- ch.start(), name=f"tutorbot:{bot_id}:ch:{ch_name}",
- )
- instance.tasks.append(ch_task)
- logger.info(
- "Reloaded channels for bot '%s': %s",
- bot_id, list(channel_manager.channels.keys()),
- )
-
# ── Listing & discovery ───────────────────────────────────────
def _discover_bot_ids(self) -> set[str]:
@@ -527,13 +636,14 @@ class TutorBotManager:
return ids
def list_bots(self) -> list[dict[str, Any]]:
- """List all known bots (running + configured on disk)."""
+ """List all known bots (running + configured on disk).
+
+ Channel field is keys-only — never expose secrets via the list endpoint.
+ """
result: dict[str, dict[str, Any]] = {}
for inst in self._bots.values():
- row = inst.to_dict()
- row["channels"] = list(inst.config.channels.keys())
- result[inst.bot_id] = row
+ result[inst.bot_id] = inst.to_dict()
for bid in self._discover_bot_ids():
if bid in result:
diff --git a/deeptutor_cli/kb.py b/deeptutor_cli/kb.py
index 39b73746d..58f4a226e 100644
--- a/deeptutor_cli/kb.py
+++ b/deeptutor_cli/kb.py
@@ -18,7 +18,7 @@ from rich.table import Table
from deeptutor.knowledge.manager import KnowledgeBaseManager
from deeptutor.services.path_service import get_path_service
-from deeptutor.services.rag.components.routing import FileTypeRouter
+from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.services.rag.factory import DEFAULT_PROVIDER
console = Console()
@@ -43,7 +43,7 @@ def _collect_documents(docs: list[str], docs_dir: Optional[str]) -> list[str]:
base = Path(docs_dir).expanduser().resolve()
if not base.exists() or not base.is_dir():
raise typer.BadParameter(f"docs directory does not exist: {base}")
- for pattern in FileTypeRouter.get_glob_patterns_for_provider(DEFAULT_PROVIDER):
+ for pattern in FileTypeRouter.get_glob_patterns():
candidates.extend(path for path in base.rglob(pattern) if path.is_file())
unique: list[str] = []
diff --git a/tests/agents/research/test_research_pipeline_rag.py b/tests/agents/research/test_research_pipeline_rag.py
new file mode 100644
index 000000000..4acd4c99a
--- /dev/null
+++ b/tests/agents/research/test_research_pipeline_rag.py
@@ -0,0 +1,146 @@
+"""
+Tests for RAG safety in the deep-research pipeline.
+
+These tests pin two contracts:
+
+* The deprecated ``DE-all`` placeholder fallback is gone — when no
+ knowledge base is configured, ``ResearchPipeline._call_tool``
+ short-circuits with a structured ``status: skipped`` JSON instead of
+ invoking the RAG service against a non-existent KB.
+* ``DecomposeAgent`` defensively disables RAG when no ``kb_name`` is
+ available, even when the runtime config still says
+ ``enable_rag: True``.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+
+from deeptutor.agents.research.agents.decompose_agent import DecomposeAgent
+from deeptutor.agents.research.research_pipeline import ResearchPipeline
+
+
+def _minimal_pipeline_config() -> dict[str, Any]:
+ return {
+ "system": {"language": "en", "verbose": False},
+ "planning": {
+ "rephrase": {"enabled": False, "max_iterations": 1},
+ "decompose": {
+ "mode": "manual",
+ "initial_subtopics": 1,
+ "auto_max_subtopics": 1,
+ },
+ },
+ "researching": {
+ "max_iterations": 1,
+ "iteration_mode": "fixed",
+ "execution_mode": "series",
+ "max_parallel_topics": 1,
+ "new_topic_min_score": 0.9,
+ "enable_rag": True,
+ "enable_web_search": False,
+ "enable_paper_search": False,
+ "enable_run_code": False,
+ "enabled_tools": ["rag"],
+ "tool_timeout": 5,
+ "tool_max_retries": 0,
+ },
+ "reporting": {
+ "min_section_length": 10,
+ "report_single_pass_threshold": 1,
+ "enable_citation_list": False,
+ "enable_inline_citations": False,
+ "deduplicate_enabled": False,
+ "style": "report",
+ "mode": "report",
+ "depth": "quick",
+ },
+ "queue": {"max_length": 2},
+ "rag": {},
+ "intent": {
+ "mode": "report",
+ "depth": "quick",
+ "sources": [],
+ "manual_subtopics": None,
+ "manual_max_iterations": None,
+ "confirmed_outline": None,
+ },
+ "tools": {"web_search": {"enabled": False}},
+ "paths": {},
+ }
+
+
+def _build_bare_pipeline(config: dict[str, Any]) -> ResearchPipeline:
+ """Build a ``ResearchPipeline`` skeleton with just the attributes
+ ``_call_tool`` reads — avoids the heavy agent-initialisation tree."""
+ pipeline = ResearchPipeline.__new__(ResearchPipeline)
+ pipeline.config = config
+ pipeline.research_id = "test"
+ pipeline.cache_dir = "/tmp/test" # type: ignore[assignment]
+ pipeline.trace_callback = None
+ pipeline._stage_events = {"planning": [], "reporting": [], "researching": []}
+ return pipeline
+
+
+async def test_research_pipeline_call_tool_rag_without_kb_returns_skipped_json() -> None:
+ """The DE-all fallback is gone: ``rag`` without a ``kb_name`` must be a no-op."""
+ pipeline = _build_bare_pipeline(_minimal_pipeline_config())
+
+ raw = await pipeline._call_tool("rag", "What is convolution?")
+ payload = json.loads(raw)
+
+ assert payload["status"] == "skipped"
+ assert payload["reason"] == "no_kb_selected"
+ assert payload["tool"] == "rag"
+
+
+async def test_research_pipeline_call_tool_unknown_tool_returns_failed_not_rag() -> None:
+ """Unknown tool types must not silently fall through to RAG anymore."""
+ pipeline = _build_bare_pipeline(_minimal_pipeline_config())
+
+ raw = await pipeline._call_tool("not_a_real_tool", "anything")
+ payload = json.loads(raw)
+
+ assert payload["status"] == "failed"
+ assert payload["reason"] == "unknown_tool"
+ assert payload["tool"] == "not_a_real_tool"
+
+
+def test_decompose_agent_disables_rag_when_no_kb_name() -> None:
+ """Defensive guard at the agent layer: no ``kb_name`` ⇒ ``enable_rag = False``."""
+ config = _minimal_pipeline_config()
+ config["rag"] = {"kb_name": None}
+ config["researching"]["enable_rag"] = True
+
+ agent = DecomposeAgent(config=config, api_key="sk-test", kb_name=None)
+
+ assert agent.kb_name is None
+ assert agent.enable_rag is False
+
+
+def test_decompose_agent_keeps_rag_when_kb_name_provided_via_kwarg() -> None:
+ config = _minimal_pipeline_config()
+ config["rag"] = {}
+ config["researching"]["enable_rag"] = True
+
+ agent = DecomposeAgent(config=config, api_key="sk-test", kb_name="my-kb")
+
+ assert agent.kb_name == "my-kb"
+ assert agent.enable_rag is True
+
+
+def test_decompose_agent_no_longer_falls_back_to_ai_textbook() -> None:
+ """The hardcoded ``ai_textbook`` fallback was removed."""
+ config = _minimal_pipeline_config()
+ config["rag"] = {}
+ config["researching"]["enable_rag"] = True
+
+ agent = DecomposeAgent(config=config, api_key="sk-test", kb_name=None)
+
+ assert agent.kb_name is None # NOT "ai_textbook"
+ assert agent.enable_rag is False
diff --git a/tests/agents/solve/test_tool_runtime.py b/tests/agents/solve/test_tool_runtime.py
index 9f89a790b..572c2e06d 100644
--- a/tests/agents/solve/test_tool_runtime.py
+++ b/tests/agents/solve/test_tool_runtime.py
@@ -131,6 +131,39 @@ async def test_solve_tool_runtime_passes_event_sink_to_registry() -> None:
]
+async def test_solve_tool_runtime_rag_without_kb_returns_graceful_skip() -> None:
+ """`rag` invoked without a kb_name must never reach the underlying RAG service.
+
+ The runtime should return a structured ``ToolResult`` describing the skip
+ so the ReAct loop can keep going (the LLM sees a clear observation and
+ can replan or finalise).
+ """
+ rag_tool = _FakeTool("rag", [ToolParameter(name="query", type="string")])
+ registry = _FakeCoreRegistry({"rag": rag_tool})
+ runtime = SolveToolRuntime(["rag"], language="en", core_registry=registry)
+
+ result = await runtime.execute("rag", "definition", kb_name=None)
+
+ assert result.success is False
+ assert result.metadata == {"skipped": True, "reason": "no_kb_selected"}
+ assert "no knowledge base" in result.content.lower()
+ assert registry.exec_calls == [], "rag must NOT be forwarded to the registry"
+
+
+async def test_solve_tool_runtime_rag_with_empty_kb_name_returns_graceful_skip() -> None:
+ rag_tool = _FakeTool("rag", [ToolParameter(name="query", type="string")])
+ registry = _FakeCoreRegistry({"rag": rag_tool})
+ runtime = SolveToolRuntime(["rag"], language="en", core_registry=registry)
+
+ result = await runtime.execute("rag", "definition", kb_name="")
+
+ assert result.success is False
+ assert result.metadata.get("reason") == "no_kb_selected"
+ assert registry.exec_calls == []
+
+
@pytest.mark.asyncio
async def test_planner_agent_skips_retrieval_when_rag_not_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
web_tool = _FakeTool("web_search", [ToolParameter(name="query", type="string")])
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index 647b2fbe9..036c2501e 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -120,20 +120,26 @@ def test_create_kb_does_not_require_llm_precheck(monkeypatch, tmp_path: Path) ->
assert manager.config["knowledge_bases"]["kb-new"]["needs_reindex"] is False
-def test_create_rejects_unregistered_provider(monkeypatch, tmp_path: Path) -> None:
+def test_create_coerces_legacy_provider_to_llamaindex(monkeypatch, tmp_path: Path) -> None:
+ """`rag_provider` is now a stub: legacy values silently normalize to llamaindex."""
manager = _FakeKBManager(tmp_path / "knowledge_bases")
monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)
+
+ async def _noop_init_task(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(knowledge_router_module, "run_initialization_task", _noop_init_task)
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": "lightrag"},
+ data={"name": "kb-legacy", "rag_provider": "lightrag"},
files=_upload_payload(),
)
- assert response.status_code == 400
- assert "Unsupported RAG provider" in response.json()["detail"]
+ assert response.status_code == 200
+ assert manager.config["knowledge_bases"]["kb-legacy"]["rag_provider"] == "llamaindex"
def test_upload_returns_409_when_kb_needs_reindex(monkeypatch, tmp_path: Path) -> None:
@@ -177,8 +183,13 @@ def test_upload_ready_kb_returns_task_id(monkeypatch, tmp_path: Path) -> None:
assert isinstance(body.get("task_id"), str) and body["task_id"]
-def test_update_config_rejects_unregistered_provider() -> None:
+def test_update_config_coerces_legacy_provider_to_llamaindex() -> None:
+ """Legacy `rag_provider` values are accepted and normalized to llamaindex."""
+
class _FakeConfigService:
+ def __init__(self) -> None:
+ self.config: dict = {}
+
def set_kb_config(self, kb_name: str, config: dict) -> None:
self.kb_name = kb_name
self.config = config
@@ -199,5 +210,5 @@ def test_update_config_rejects_unregistered_provider() -> None:
json={"rag_provider": "raganything"},
)
- assert response.status_code == 400
- assert "Unsupported RAG provider" in response.json()["detail"]
+ assert response.status_code in {200, 204}
+ assert fake_service.config.get("rag_provider") == "llamaindex"
diff --git a/tests/api/test_tutorbot_channel_schema.py b/tests/api/test_tutorbot_channel_schema.py
new file mode 100644
index 000000000..9981d2f1f
--- /dev/null
+++ b/tests/api/test_tutorbot_channel_schema.py
@@ -0,0 +1,185 @@
+"""Tests for the schema-driven channels endpoint helpers.
+
+Covers:
+* ``resolve_config_model``: maps each ``XxxChannel`` to its ``XxxConfig``.
+* ``inline_refs``: flattens nested model ``$ref``s (slack ``dm`` subtree).
+* ``collect_secret_fields``: only flags **string-typed** secret-looking keys
+ (so e.g. ``user_token_read_only: bool`` is excluded).
+* ``GET /api/v1/tutorbot/channels/schema`` integration: shape, snake_case
+ property names, and that telegram/slack/discord schemas survive the trip.
+"""
+
+from __future__ import annotations
+
+from fastapi.testclient import TestClient
+import pytest
+
+from deeptutor.api.routers._tutorbot_channel_schema import (
+ all_channel_schemas,
+ channel_schema_payload,
+ collect_secret_fields,
+ inline_refs,
+ resolve_config_model,
+)
+
+
+class TestResolveConfigModel:
+ def test_telegram_pairs_with_telegram_config(self) -> None:
+ from deeptutor.tutorbot.channels.telegram import TelegramChannel, TelegramConfig
+
+ assert resolve_config_model(TelegramChannel) is TelegramConfig
+
+ def test_slack_pairs_with_slack_config(self) -> None:
+ from deeptutor.tutorbot.channels.slack import SlackChannel, SlackConfig
+
+ assert resolve_config_model(SlackChannel) is SlackConfig
+
+ def test_discord_pairs_with_discord_config(self) -> None:
+ from deeptutor.tutorbot.channels.discord import DiscordChannel, DiscordConfig
+
+ assert resolve_config_model(DiscordChannel) is DiscordConfig
+
+
+class TestInlineRefs:
+ def test_inlines_simple_def(self) -> None:
+ schema = {
+ "type": "object",
+ "properties": {"dm": {"$ref": "#/$defs/SlackDMConfig"}},
+ "$defs": {
+ "SlackDMConfig": {
+ "type": "object",
+ "properties": {"enabled": {"type": "boolean"}},
+ }
+ },
+ }
+ out = inline_refs(schema)
+ assert "$defs" not in out
+ assert out["properties"]["dm"]["type"] == "object"
+ assert out["properties"]["dm"]["properties"]["enabled"]["type"] == "boolean"
+
+ def test_per_field_overrides_take_precedence(self) -> None:
+ # Pydantic sometimes emits {"$ref": "...", "description": "..."}; the
+ # description should override the referenced model's description.
+ schema = {
+ "type": "object",
+ "properties": {
+ "child": {"$ref": "#/$defs/Foo", "description": "override"},
+ },
+ "$defs": {
+ "Foo": {"type": "object", "description": "original"},
+ },
+ }
+ out = inline_refs(schema)
+ assert out["properties"]["child"]["description"] == "override"
+
+
+class TestCollectSecretFields:
+ def test_flags_string_token_field(self) -> None:
+ schema = {
+ "properties": {
+ "token": {"type": "string"},
+ "enabled": {"type": "boolean"},
+ }
+ }
+ assert collect_secret_fields(schema) == ["token"]
+
+ def test_skips_boolean_with_secret_substring(self) -> None:
+ # Slack's ``user_token_read_only`` is a flag, not a secret.
+ schema = {
+ "properties": {
+ "user_token_read_only": {"type": "boolean"},
+ "bot_token": {"type": "string"},
+ }
+ }
+ assert collect_secret_fields(schema) == ["bot_token"]
+
+ def test_walks_nested_objects(self) -> None:
+ schema = {
+ "properties": {
+ "dm": {
+ "type": "object",
+ "properties": {"webhook_secret": {"type": "string"}},
+ },
+ }
+ }
+ assert collect_secret_fields(schema) == ["dm.webhook_secret"]
+
+ def test_handles_nullable_strings(self) -> None:
+ # Pydantic's ``Optional[str]`` becomes ``anyOf: [{type: string}, {type: null}]``.
+ schema = {
+ "properties": {
+ "encrypt_key": {"anyOf": [{"type": "string"}, {"type": "null"}]},
+ }
+ }
+ assert collect_secret_fields(schema) == ["encrypt_key"]
+
+
+class TestChannelSchemaPayload:
+ def test_telegram_payload_shape(self) -> None:
+ from deeptutor.tutorbot.channels.telegram import TelegramChannel
+
+ payload = channel_schema_payload(TelegramChannel)
+ assert payload is not None
+ assert payload["name"] == "telegram"
+ assert payload["display_name"] == "Telegram"
+ assert payload["secret_fields"] == ["token"]
+ # Snake_case wire format (matches the storage form).
+ props = payload["json_schema"]["properties"]
+ assert "allow_from" in props and "allowFrom" not in props
+ assert payload["default_config"]["enabled"] is False
+
+ def test_slack_dm_subtree_inlined(self) -> None:
+ from deeptutor.tutorbot.channels.slack import SlackChannel
+
+ payload = channel_schema_payload(SlackChannel)
+ assert payload is not None
+ dm = payload["json_schema"]["properties"]["dm"]
+ assert dm["type"] == "object"
+ assert "enabled" in dm["properties"]
+ # Bool flags whose names contain "token" must NOT be flagged secret.
+ assert "user_token_read_only" not in payload["secret_fields"]
+ assert "bot_token" in payload["secret_fields"]
+
+
+class TestEndpoint:
+ @pytest.fixture
+ def client(self) -> TestClient:
+ # Build a minimal FastAPI app with just the tutorbot router; the
+ # ``/channels/schema`` endpoint doesn't touch the manager so no
+ # fixturing of ``get_tutorbot_manager`` is needed.
+ from fastapi import FastAPI
+
+ from deeptutor.api.routers import tutorbot as tutorbot_router
+
+ app = FastAPI()
+ app.include_router(tutorbot_router.router, prefix="/api/v1/tutorbot")
+ return TestClient(app)
+
+ def test_returns_channels_and_global(self, client: TestClient) -> None:
+ res = client.get("/api/v1/tutorbot/channels/schema")
+ assert res.status_code == 200
+ body = res.json()
+ assert set(body.keys()) >= {"channels", "global"}
+ # Telegram is always installed (no extra deps).
+ assert "telegram" in body["channels"]
+
+ def test_telegram_entry_has_secret_fields(self, client: TestClient) -> None:
+ res = client.get("/api/v1/tutorbot/channels/schema")
+ tg = res.json()["channels"]["telegram"]
+ assert tg["secret_fields"] == ["token"]
+ assert "token" in tg["json_schema"]["properties"]
+
+ def test_global_schema_uses_snake_case(self, client: TestClient) -> None:
+ res = client.get("/api/v1/tutorbot/channels/schema")
+ global_props = res.json()["global"]["json_schema"]["properties"]
+ assert "send_progress" in global_props
+ assert "send_tool_hints" in global_props
+
+
+class TestAllChannelSchemas:
+ def test_returns_at_least_telegram(self) -> None:
+ out = all_channel_schemas()
+ assert "telegram" in out
+ # Every payload has the four documented keys.
+ for entry in out.values():
+ assert {"name", "display_name", "default_config", "secret_fields", "json_schema"} <= entry.keys()
diff --git a/tests/api/test_tutorbot_router.py b/tests/api/test_tutorbot_router.py
index 47009b3a8..d4f81a5d5 100644
--- a/tests/api/test_tutorbot_router.py
+++ b/tests/api/test_tutorbot_router.py
@@ -253,39 +253,57 @@ class TestCreateBotExplicitClearSemantics:
assert saved["config"].description == "Disk Desc"
-class TestGetBotStoppedReturnsFullChannels:
- """GET /{bot_id} must return nested channel config when the bot is not running."""
+class TestGetBotStoppedSecretHandling:
+ """GET /{bot_id} masks channel secrets by default; ?include_secrets=true reveals them."""
- def test_get_stopped_bot_includes_telegram_config(self, monkeypatch):
- from deeptutor.services.tutorbot.manager import BotConfig
+ _CHANNELS = {
+ "telegram": {"enabled": True, "token": "123:ABC", "allow_from": ["1"]},
+ "send_progress": True,
+ "send_tool_hints": False,
+ }
- channels = {"telegram": {"enabled": True, "token": "x:y", "allow_from": ["1"]}}
+ def _client(self, monkeypatch):
+ from deeptutor.services.tutorbot.manager import BotConfig
class FakeMgr:
def get_bot(self, bot_id: str):
return None
def load_bot_config(self, bot_id: str) -> BotConfig | None:
- return BotConfig(name="b", channels=channels)
+ return BotConfig(name="b", channels=TestGetBotStoppedSecretHandling._CHANNELS)
tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")
monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: FakeMgr())
app = FastAPI()
app.include_router(tutorbot_router_mod.router, prefix="/api/v1/tutorbot")
- client = TestClient(app)
+ return TestClient(app)
+ def test_default_get_masks_token(self, monkeypatch):
+ client = self._client(monkeypatch)
resp = client.get("/api/v1/tutorbot/b")
assert resp.status_code == 200
body = resp.json()
- assert body["channels"] == channels
+ # Structure preserved, but token replaced with mask
+ assert body["channels"]["telegram"]["enabled"] is True
+ assert body["channels"]["telegram"]["allow_from"] == ["1"]
+ assert body["channels"]["telegram"]["token"] == "***"
+ assert body["channels"]["send_progress"] is True
assert body["running"] is False
+ assert body["last_reload_error"] is None
+
+ def test_explicit_include_secrets_reveals_token(self, monkeypatch):
+ client = self._client(monkeypatch)
+ resp = client.get("/api/v1/tutorbot/b?include_secrets=true")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["channels"]["telegram"]["token"] == "123:ABC"
class TestPatchBotStoppedAndRunning:
"""PATCH must work when the bot is stopped; running + channels triggers reload."""
- def test_patch_stopped_saves_and_returns_channels(self, monkeypatch):
+ def test_patch_stopped_saves_and_masks_response(self, monkeypatch):
from deeptutor.services.tutorbot.manager import BotConfig
saved_cfg: list[BotConfig | None] = []
@@ -313,9 +331,13 @@ class TestPatchBotStoppedAndRunning:
new_ch = {"telegram": {"enabled": True, "token": "1:2"}}
resp = client.patch("/api/v1/tutorbot/b", json={"channels": new_ch})
assert resp.status_code == 200
- assert resp.json()["channels"] == new_ch
+ body = resp.json()
+ # Disk write keeps the real value
assert len(saved_cfg) == 1
assert saved_cfg[0].channels == new_ch
+ # Response masks the token
+ assert body["channels"]["telegram"]["token"] == "***"
+ assert body["channels"]["telegram"]["enabled"] is True
def test_patch_running_channels_calls_reload(self, monkeypatch):
from deeptutor.services.tutorbot.manager import BotConfig
@@ -326,17 +348,19 @@ class TestPatchBotStoppedAndRunning:
def __init__(self):
self.config = BotConfig(name="b", channels={"telegram": {"enabled": True}})
self._running = True
+ self.last_reload_error = None
@property
def running(self) -> bool:
return self._running
- def to_dict(self):
+ def to_dict(self, *, include_secrets: bool = False, mask_secrets: bool = False):
return {
"bot_id": "b",
"name": self.config.name,
- "channels": self.config.channels,
+ "channels": [] if not (include_secrets or mask_secrets) else self.config.channels,
"running": True,
+ "last_reload_error": self.last_reload_error,
}
inst = FakeInst()
@@ -361,3 +385,79 @@ class TestPatchBotStoppedAndRunning:
resp = client.patch("/api/v1/tutorbot/b", json={"channels": {"telegram": {"enabled": False}}})
assert resp.status_code == 200
assert reloaded == [True]
+
+ def test_patch_invalid_channels_rejected_422(self, monkeypatch):
+ """Malformed channels must be rejected at the boundary, not after disk write."""
+ from deeptutor.services.tutorbot.manager import BotConfig
+
+ saved_cfg: list[BotConfig] = []
+
+ class FakeMgr:
+ def get_bot(self, bot_id: str):
+ return None
+
+ def load_bot_config(self, bot_id: str) -> BotConfig | None:
+ return BotConfig(name="b")
+
+ def save_bot_config(self, bot_id: str, config: BotConfig, *, auto_start: bool = True) -> None:
+ saved_cfg.append(config)
+
+ tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")
+ monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: FakeMgr())
+
+ app = FastAPI()
+ app.include_router(tutorbot_router_mod.router, prefix="/api/v1/tutorbot")
+ client = TestClient(app)
+
+ # send_progress should be a bool, not an int-string-list garbage value;
+ # unknown extras are allowed (extra="allow" on ChannelsConfig), so we
+ # use a clearly typed-wrong primitive for a known field.
+ resp = client.patch(
+ "/api/v1/tutorbot/b",
+ json={"channels": {"send_progress": ["nope"]}},
+ )
+ assert resp.status_code == 422
+ # IMPORTANT: nothing should have been written to disk
+ assert saved_cfg == []
+
+ def test_patch_running_reload_failure_returns_500(self, monkeypatch):
+ """If reload_channels raises, PATCH responds with 500 and a hint."""
+ from deeptutor.services.tutorbot.manager import BotConfig
+
+ class FakeInst:
+ def __init__(self):
+ self.config = BotConfig(name="b", channels={"telegram": {"enabled": True}})
+ self.last_reload_error = None
+
+ @property
+ def running(self) -> bool:
+ return True
+
+ def to_dict(self, *, include_secrets: bool = False, mask_secrets: bool = False):
+ return {"bot_id": "b", "channels": [], "running": True}
+
+ class FakeMgr:
+ def get_bot(self, bot_id: str):
+ return FakeInst()
+
+ def save_bot_config(self, bot_id: str, config: BotConfig, *, auto_start: bool = True) -> None:
+ pass
+
+ async def reload_channels(self, bot_id: str) -> None:
+ raise RuntimeError("telegram bind failed")
+
+ tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")
+ monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: FakeMgr())
+
+ app = FastAPI()
+ app.include_router(tutorbot_router_mod.router, prefix="/api/v1/tutorbot")
+ client = TestClient(app)
+
+ resp = client.patch(
+ "/api/v1/tutorbot/b",
+ json={"channels": {"telegram": {"enabled": True, "token": "1:2"}}},
+ )
+ assert resp.status_code == 500
+ detail = resp.json()["detail"]
+ assert "RuntimeError" in detail
+ assert "stopping and starting" in detail.lower()
diff --git a/tests/capabilities/test_rag_consistency.py b/tests/capabilities/test_rag_consistency.py
new file mode 100644
index 000000000..d72b34fb4
--- /dev/null
+++ b/tests/capabilities/test_rag_consistency.py
@@ -0,0 +1,233 @@
+"""
+Tests for RAG/KB consistency normalization at the capability layer.
+
+These tests pin the contract that:
+
+* ``deep_solve`` strips ``rag`` from the effective tool set when no
+ knowledge base is attached, and emits a warning so the UI can surface
+ the mismatch.
+* ``deep_research`` strips ``kb`` from the effective sources list when
+ no knowledge base is attached, and surfaces a clear error if all
+ sources end up empty.
+
+Both behaviours guarantee that no downstream agent or pipeline ever
+attempts a RAG call against a missing/placeholder knowledge base.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.core.stream_bus import StreamBus
+
+
+async def _drain(bus: StreamBus, task) -> list[StreamEvent]:
+ await task
+ await bus.close()
+ return [event async for event in bus.subscribe()]
+
+
+def _fake_llm_config() -> MagicMock:
+ cfg = MagicMock()
+ cfg.api_key = "sk-test"
+ cfg.base_url = None
+ cfg.api_version = None
+ return cfg
+
+
+# ---------------------------------------------------------------------------
+# deep_solve: rag without KB → tool stripped, warning emitted
+# ---------------------------------------------------------------------------
+
+
+async def test_deep_solve_strips_rag_when_no_knowledge_base() -> None:
+ from deeptutor.capabilities.deep_solve import DeepSolveCapability
+
+ captured_kwargs: dict[str, Any] = {}
+
+ class _FakeSolver:
+ def __init__(self, **kwargs: Any) -> None:
+ captured_kwargs.update(kwargs)
+
+ async def ainit(self) -> None:
+ return None
+
+ def set_trace_callback(self, _cb: Any) -> None:
+ return None
+
+ async def solve(self, **_kwargs: Any) -> dict[str, Any]:
+ return {"final_answer": "ok", "metadata": {}}
+
+ capability = DeepSolveCapability()
+ bus = StreamBus()
+ context = UnifiedContext(
+ user_message="solve x^2 = 4",
+ active_capability="deep_solve",
+ enabled_tools=["rag", "web_search"],
+ knowledge_bases=[], # explicitly empty
+ language="en",
+ )
+
+ with patch(
+ "deeptutor.agents.solve.main_solver.MainSolver",
+ new=_FakeSolver,
+ ), patch(
+ "deeptutor.services.llm.config.get_llm_config",
+ return_value=_fake_llm_config(),
+ ):
+ events = await _drain(bus, capability.run(context, bus))
+
+ # rag must NOT be in the enabled_tools we forwarded to MainSolver
+ assert "rag" not in captured_kwargs["enabled_tools"]
+ assert "web_search" in captured_kwargs["enabled_tools"]
+ assert captured_kwargs["kb_name"] is None
+ assert captured_kwargs["disable_planner_retrieve"] is True
+
+ # And a warning progress event should have been emitted
+ warnings = [
+ e for e in events
+ if e.type == StreamEventType.PROGRESS
+ and (e.metadata or {}).get("reason") == "rag_without_kb"
+ ]
+ assert warnings, "expected a rag_without_kb warning event"
+
+
+async def test_deep_solve_keeps_rag_when_knowledge_base_attached() -> None:
+ from deeptutor.capabilities.deep_solve import DeepSolveCapability
+
+ captured_kwargs: dict[str, Any] = {}
+
+ class _FakeSolver:
+ def __init__(self, **kwargs: Any) -> None:
+ captured_kwargs.update(kwargs)
+
+ async def ainit(self) -> None:
+ return None
+
+ def set_trace_callback(self, _cb: Any) -> None:
+ return None
+
+ async def solve(self, **_kwargs: Any) -> dict[str, Any]:
+ return {"final_answer": "ok", "metadata": {}}
+
+ capability = DeepSolveCapability()
+ bus = StreamBus()
+ context = UnifiedContext(
+ user_message="solve x^2 = 4",
+ active_capability="deep_solve",
+ enabled_tools=["rag", "web_search"],
+ knowledge_bases=["my-kb"],
+ language="en",
+ )
+
+ with patch(
+ "deeptutor.agents.solve.main_solver.MainSolver",
+ new=_FakeSolver,
+ ), patch(
+ "deeptutor.services.llm.config.get_llm_config",
+ return_value=_fake_llm_config(),
+ ):
+ await _drain(bus, capability.run(context, bus))
+
+ assert "rag" in captured_kwargs["enabled_tools"]
+ assert captured_kwargs["kb_name"] == "my-kb"
+ assert captured_kwargs["disable_planner_retrieve"] is False
+
+
+# ---------------------------------------------------------------------------
+# deep_research: kb in sources without KB → kb dropped or hard error
+# ---------------------------------------------------------------------------
+
+
+async def test_deep_research_drops_kb_source_when_no_knowledge_base() -> None:
+ from deeptutor.capabilities.deep_research import DeepResearchCapability
+
+ captured_config: dict[str, Any] = {}
+
+ async def _fake_outline(self, **kwargs: Any): # noqa: ARG001
+ captured_config.update(kwargs.get("config") or {})
+ return [{"title": "Subtopic 1", "overview": "Overview 1"}]
+
+ capability = DeepResearchCapability()
+ bus = StreamBus()
+ context = UnifiedContext(
+ user_message="A topic to research",
+ active_capability="deep_research",
+ enabled_tools=["rag", "web_search"],
+ knowledge_bases=[],
+ config_overrides={
+ "mode": "report",
+ "depth": "standard",
+ "sources": ["kb", "web"], # kb requested but no KB attached
+ },
+ language="en",
+ )
+
+ with patch.object(
+ DeepResearchCapability,
+ "_generate_outline_preview",
+ new=_fake_outline,
+ ), patch(
+ "deeptutor.services.llm.config.get_llm_config",
+ return_value=_fake_llm_config(),
+ ), patch(
+ "deeptutor.services.config.load_config_with_main",
+ return_value={},
+ ):
+ events = await _drain(bus, capability.run(context, bus))
+
+ # The runtime config must NOT enable RAG, but must still allow web.
+ researching = captured_config.get("researching", {})
+ assert researching.get("enable_rag") is False
+ assert researching.get("enable_web_search") is True
+ # rag intent stripped from request_config sources
+ assert captured_config["intent"]["sources"] == ["web"]
+
+ # A warning progress event must be present
+ warnings = [
+ e for e in events
+ if e.type == StreamEventType.PROGRESS
+ and (e.metadata or {}).get("reason") == "kb_without_kb_name"
+ ]
+ assert warnings, "expected a kb_without_kb_name warning event"
+
+
+async def test_deep_research_errors_when_only_kb_source_and_no_knowledge_base() -> None:
+ from deeptutor.capabilities.deep_research import DeepResearchCapability
+
+ capability = DeepResearchCapability()
+ bus = StreamBus()
+ context = UnifiedContext(
+ user_message="topic",
+ active_capability="deep_research",
+ enabled_tools=["rag"],
+ knowledge_bases=[],
+ config_overrides={
+ "mode": "report",
+ "depth": "standard",
+ "sources": ["kb"], # ONLY kb, and no KB attached
+ },
+ language="en",
+ )
+
+ with patch(
+ "deeptutor.services.llm.config.get_llm_config",
+ return_value=_fake_llm_config(),
+ ), patch(
+ "deeptutor.services.config.load_config_with_main",
+ return_value={},
+ ):
+ events = await _drain(bus, capability.run(context, bus))
+
+ errors = [e for e in events if e.type == StreamEventType.ERROR]
+ assert errors, "expected an error event when no usable source remains"
+ assert "source" in errors[0].content.lower()
diff --git a/tests/services/config/test_knowledge_base_config.py b/tests/services/config/test_knowledge_base_config.py
new file mode 100644
index 000000000..4917bde04
--- /dev/null
+++ b/tests/services/config/test_knowledge_base_config.py
@@ -0,0 +1,147 @@
+"""Tests for KnowledgeBaseConfigService stub + legacy-config migration."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from deeptutor.services.config.knowledge_base_config import (
+ KnowledgeBaseConfigService,
+)
+
+
+def _write_kb_config(path: Path, payload: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(payload), encoding="utf-8")
+
+
+def fresh_service(tmp_path: Path) -> KnowledgeBaseConfigService:
+ """A KBConfigService bound to a tmp config path, bypassing the singleton."""
+ return KnowledgeBaseConfigService(config_path=tmp_path / "kb_config.json")
+
+
+class TestStubProviderApi:
+ def test_get_rag_provider_always_llamaindex(self, fresh_service) -> None:
+ assert fresh_service.get_rag_provider("any-kb") == "llamaindex"
+
+ def test_set_rag_provider_coerces_legacy_to_llamaindex(self, fresh_service) -> None:
+ fresh_service.set_rag_provider("kb-1", "lightrag")
+ cfg = fresh_service.get_kb_config("kb-1")
+ assert cfg["rag_provider"] == "llamaindex"
+
+ def test_set_rag_provider_coerces_unknown_to_llamaindex(self, fresh_service) -> None:
+ fresh_service.set_rag_provider("kb-2", "totally-unknown")
+ cfg = fresh_service.get_kb_config("kb-2")
+ assert cfg["rag_provider"] == "llamaindex"
+
+ def test_get_kb_config_overrides_provider_field(self, fresh_service) -> None:
+ """Even if a stale entry leaks `rag_provider: lightrag`, reads return llamaindex."""
+ fresh_service._config.setdefault("knowledge_bases", {})["kb-3"] = {
+ "path": "kb-3",
+ "rag_provider": "lightrag",
+ }
+ cfg = fresh_service.get_kb_config("kb-3")
+ assert cfg["rag_provider"] == "llamaindex"
+
+
+class TestPayloadNormalizationOnLoad:
+ def test_legacy_provider_in_file_is_rewritten_and_marks_reindex(self, tmp_path: Path) -> None:
+ config_path = tmp_path / "kb_config.json"
+ _write_kb_config(
+ config_path,
+ {
+ "defaults": {"rag_provider": "lightrag", "search_mode": "hybrid"},
+ "knowledge_bases": {
+ "old-kb": {"path": "old-kb", "rag_provider": "lightrag"},
+ },
+ },
+ )
+
+ service = KnowledgeBaseConfigService(config_path=config_path)
+ kb = service._config["knowledge_bases"]["old-kb"]
+ assert kb["rag_provider"] == "llamaindex"
+ assert kb["needs_reindex"] is True
+
+ defaults = service._config["defaults"]
+ assert defaults["rag_provider"] == "llamaindex"
+
+ def test_existing_llamaindex_kb_is_left_alone(self, tmp_path: Path) -> None:
+ config_path = tmp_path / "kb_config.json"
+ _write_kb_config(
+ config_path,
+ {
+ "defaults": {"rag_provider": "llamaindex"},
+ "knowledge_bases": {
+ "fresh-kb": {"path": "fresh-kb", "rag_provider": "llamaindex"},
+ },
+ },
+ )
+
+ service = KnowledgeBaseConfigService(config_path=config_path)
+ kb = service._config["knowledge_bases"]["fresh-kb"]
+ assert kb["rag_provider"] == "llamaindex"
+ assert kb.get("needs_reindex", False) is False
+
+ def test_legacy_storage_dir_marks_reindex(self, tmp_path: Path) -> None:
+ """If the on-disk storage uses the old layout, force a reindex flag."""
+ config_path = tmp_path / "kb_config.json"
+ kb_dir = tmp_path / "stale-kb"
+ (kb_dir / "rag_storage").mkdir(parents=True)
+
+ _write_kb_config(
+ config_path,
+ {
+ "defaults": {"rag_provider": "llamaindex"},
+ "knowledge_bases": {
+ "stale-kb": {"path": "stale-kb", "rag_provider": "llamaindex"},
+ },
+ },
+ )
+
+ service = KnowledgeBaseConfigService(config_path=config_path)
+ kb = service._config["knowledge_bases"]["stale-kb"]
+ assert kb["needs_reindex"] is True
+
+ def test_modern_storage_dir_does_not_trigger_reindex(self, tmp_path: Path) -> None:
+ config_path = tmp_path / "kb_config.json"
+ kb_dir = tmp_path / "modern-kb"
+ (kb_dir / "llamaindex_storage").mkdir(parents=True)
+ (kb_dir / "rag_storage").mkdir(parents=True) # legacy dir co-existing
+
+ _write_kb_config(
+ config_path,
+ {
+ "knowledge_bases": {
+ "modern-kb": {"path": "modern-kb", "rag_provider": "llamaindex"},
+ },
+ },
+ )
+
+ service = KnowledgeBaseConfigService(config_path=config_path)
+ kb = service._config["knowledge_bases"]["modern-kb"]
+ # legacy dir present + modern dir present => no forced reindex
+ assert kb.get("needs_reindex", False) is False
+
+
+class TestPersistence:
+ def test_set_kb_config_normalizes_on_save(self, tmp_path: Path) -> None:
+ config_path = tmp_path / "kb_config.json"
+ service = KnowledgeBaseConfigService(config_path=config_path)
+ service.set_kb_config("new-kb", {"rag_provider": "raganything", "description": "x"})
+
+ on_disk = json.loads(config_path.read_text(encoding="utf-8"))
+ assert on_disk["knowledge_bases"]["new-kb"]["rag_provider"] == "llamaindex"
+ assert on_disk["knowledge_bases"]["new-kb"]["description"] == "x"
+
+ def test_search_mode_is_preserved(self, fresh_service) -> None:
+ fresh_service.set_search_mode("kb", "naive")
+ assert fresh_service.get_search_mode("kb") == "naive"
+
+ def test_set_default_kb(self, fresh_service) -> None:
+ fresh_service.set_default_kb("primary")
+ assert fresh_service.get_default_kb() == "primary"
+ fresh_service.set_default_kb(None)
+ assert fresh_service.get_default_kb() is None
diff --git a/tests/services/rag/test_file_routing.py b/tests/services/rag/test_file_routing.py
new file mode 100644
index 000000000..6ae44154c
--- /dev/null
+++ b/tests/services/rag/test_file_routing.py
@@ -0,0 +1,108 @@
+"""Tests for FileTypeRouter classification and helper methods."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from deeptutor.services.rag.file_routing import (
+ DocumentType,
+ FileTypeRouter,
+)
+
+
+class TestExtensionClassification:
+ @pytest.mark.parametrize(
+ "filename, expected",
+ [
+ ("doc.pdf", DocumentType.PDF),
+ ("DOC.PDF", DocumentType.PDF), # case-insensitive
+ ("notes.md", DocumentType.TEXT),
+ ("readme.MARKDOWN", DocumentType.TEXT),
+ ("data.json", DocumentType.TEXT),
+ ("script.py", DocumentType.TEXT),
+ ("config.yaml", DocumentType.TEXT),
+ ("paper.docx", DocumentType.DOCX),
+ ("photo.png", DocumentType.IMAGE),
+ ],
+ )
+ def test_known_extensions(self, filename: str, expected: DocumentType) -> None:
+ assert FileTypeRouter.get_document_type(filename) == expected
+
+
+class TestUnknownExtensionFallback:
+ def test_unknown_extension_with_text_content_is_text(self, tmp_path: Path) -> None:
+ path = tmp_path / "data.weirdext"
+ path.write_text("hello world", encoding="utf-8")
+ assert FileTypeRouter.get_document_type(str(path)) == DocumentType.TEXT
+
+ def test_unknown_extension_with_binary_content_is_unknown(self, tmp_path: Path) -> None:
+ path = tmp_path / "blob.bin"
+ path.write_bytes(b"\x00\x01\x02\xff")
+ assert FileTypeRouter.get_document_type(str(path)) == DocumentType.UNKNOWN
+
+
+class TestClassifyFiles:
+ def test_routes_pdf_to_parser_text_to_text(self, tmp_path: Path) -> None:
+ pdf = tmp_path / "a.pdf"
+ pdf.write_bytes(b"%PDF-1.4")
+ txt = tmp_path / "a.txt"
+ txt.write_text("hi")
+ png = tmp_path / "a.png"
+ png.write_bytes(b"\x89PNG\r\n")
+
+ cls = FileTypeRouter.classify_files([str(pdf), str(txt), str(png)])
+ assert cls.parser_files == [str(pdf)]
+ assert cls.text_files == [str(txt)]
+ assert cls.unsupported == [str(png)]
+
+ def test_empty_input_yields_empty_groups(self) -> None:
+ cls = FileTypeRouter.classify_files([])
+ assert cls.parser_files == []
+ assert cls.text_files == []
+ assert cls.unsupported == []
+
+
+class TestSupportedExtensionsAndGlobs:
+ def test_get_supported_extensions_covers_pdf_and_text(self) -> None:
+ exts = FileTypeRouter.get_supported_extensions()
+ assert ".pdf" in exts
+ assert ".md" in exts
+ assert ".txt" in exts
+
+ def test_glob_patterns_match_supported_extensions(self) -> None:
+ exts = FileTypeRouter.get_supported_extensions()
+ patterns = FileTypeRouter.get_glob_patterns()
+ assert {f"*{ext}" for ext in exts} == set(patterns)
+ # Glob output should be deterministic / sorted
+ assert patterns == sorted(patterns)
+
+
+class TestQuickHelpers:
+ def test_needs_parser_for_pdf(self) -> None:
+ assert FileTypeRouter.needs_parser("paper.pdf") is True
+
+ def test_needs_parser_false_for_text(self) -> None:
+ assert FileTypeRouter.needs_parser("notes.md") is False
+
+ def test_is_text_readable_for_text(self) -> None:
+ assert FileTypeRouter.is_text_readable("readme.md") is True
+
+ def test_is_text_readable_false_for_pdf(self) -> None:
+ assert FileTypeRouter.is_text_readable("doc.pdf") is False
+
+
+class TestReadTextFile:
+ async def test_reads_utf8(self, tmp_path: Path) -> None:
+ path = tmp_path / "u.txt"
+ path.write_text("héllo", encoding="utf-8")
+ content = await FileTypeRouter.read_text_file(str(path))
+ assert content == "héllo"
+
+ async def test_reads_gbk_fallback(self, tmp_path: Path) -> None:
+ path = tmp_path / "g.txt"
+ path.write_bytes("中文测试".encode("gbk"))
+ content = await FileTypeRouter.read_text_file(str(path))
+ assert "中文" in content
diff --git a/tests/services/rag/test_rag_pipelines.py b/tests/services/rag/test_rag_pipelines.py
index b4e46131a..a2a829d20 100644
--- a/tests/services/rag/test_rag_pipelines.py
+++ b/tests/services/rag/test_rag_pipelines.py
@@ -1,94 +1,146 @@
-"""RAG provider registry and tool integration tests (llamaindex-only)."""
+"""RAGService end-to-end behavior tests (with a fake pipeline)."""
from __future__ import annotations
-import os
+from typing import Any, Dict
import pytest
+from deeptutor.services.rag.service import RAGService
-def test_list_available_providers_only_llamaindex() -> None:
- """Provider list should expose only llamaindex."""
- from deeptutor.tools.rag_tool import get_available_providers
- providers = get_available_providers()
- assert [p["id"] for p in providers] == ["llamaindex"]
+class _FakePipeline:
+ """Minimal pipeline stub that records calls and returns canned results."""
+ def __init__(self, search_result: Dict[str, Any] | None = None) -> None:
+ self.calls: list[dict] = []
+ self.search_result = search_result or {
+ "answer": "fake answer",
+ "sources": [{"id": 1}],
+ "provider": "lightrag", # deliberately wrong; service must overwrite
+ }
-def test_factory_has_pipeline_only_llamaindex() -> None:
- """Factory should only report llamaindex as selectable provider."""
- from deeptutor.services.rag.factory import has_pipeline
+ async def initialize(self, kb_name: str, file_paths, **kwargs) -> bool:
+ self.calls.append({"op": "initialize", "kb_name": kb_name, "files": list(file_paths)})
+ return True
- assert has_pipeline("llamaindex") is True
- assert has_pipeline("lightrag") is False
- assert has_pipeline("raganything") is False
- assert has_pipeline("nonexistent") is False
+ async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
+ self.calls.append({"op": "search", "query": query, "kb_name": kb_name, "kwargs": kwargs})
+ return dict(self.search_result)
+ async def delete(self, kb_name: str) -> bool:
+ self.calls.append({"op": "delete", "kb_name": kb_name})
+ return True
-def test_normalize_legacy_provider_aliases() -> None:
- """Legacy provider names should normalize to llamaindex."""
- from deeptutor.services.rag.factory import normalize_provider_name
- assert normalize_provider_name("llamaindex") == "llamaindex"
- assert normalize_provider_name("lightrag") == "llamaindex"
- assert normalize_provider_name("raganything") == "llamaindex"
- assert normalize_provider_name("raganything_docling") == "llamaindex"
+def fake_service(tmp_path) -> tuple[RAGService, _FakePipeline]:
+ pipeline = _FakePipeline()
+ service = RAGService(kb_base_dir=str(tmp_path))
+ service._pipeline = pipeline # type: ignore[attr-defined]
+ return service, pipeline
-def test_get_current_provider_normalizes_env(monkeypatch: pytest.MonkeyPatch) -> None:
- """Current provider should normalize legacy env values."""
- from deeptutor.tools.rag_tool import get_current_provider
+def test_provider_argument_is_silently_ignored(tmp_path) -> None:
+ """Constructor accepts ``provider`` for back-compat but always uses llamaindex."""
+ service = RAGService(kb_base_dir=str(tmp_path), provider="lightrag")
+ assert service.provider == "llamaindex"
- monkeypatch.setenv("RAG_PROVIDER", "lightrag")
- assert get_current_provider() == "llamaindex"
- monkeypatch.setenv("RAG_PROVIDER", "llamaindex")
- assert get_current_provider() == "llamaindex"
+async def test_search_force_overwrites_provider_in_result(fake_service) -> None:
+ """Even if the underlying pipeline lies about its provider, RAGService normalizes."""
+ service, pipeline = fake_service
+ pipeline.search_result = {"answer": "x", "provider": "raganything"}
- monkeypatch.delenv("RAG_PROVIDER", raising=False)
- assert get_current_provider() == "llamaindex"
+ result = await service.search(query="hello", kb_name="kb")
+ assert result["provider"] == "llamaindex"
-def test_get_pipeline_llamaindex_interface() -> None:
- """LlamaIndex pipeline should be constructible with optional dependency installed."""
- from deeptutor.services.rag.factory import get_pipeline
+async def test_search_drops_mode_kwarg_before_calling_pipeline(fake_service) -> None:
+ """The ``mode`` kwarg is intentionally consumed by the service layer."""
+ service, pipeline = fake_service
+ await service.search(query="hi", kb_name="kb", mode="hybrid", top_k=5)
- try:
- pipeline = get_pipeline("llamaindex")
- except ValueError as exc:
- pytest.skip(f"LlamaIndex optional dependency missing: {exc}")
+ last = pipeline.calls[-1]
+ assert last["op"] == "search"
+ assert "mode" not in last["kwargs"]
+ assert last["kwargs"].get("top_k") == 5
- assert hasattr(pipeline, "initialize")
- assert hasattr(pipeline, "search")
- assert hasattr(pipeline, "delete")
+async def test_search_aliases_answer_and_content(fake_service) -> None:
+ """Pipelines that only return ``content`` should still expose ``answer`` and vice versa."""
+ service, pipeline = fake_service
-def test_get_pipeline_invalid_raises() -> None:
- """Unknown provider names should raise explicit error."""
- from deeptutor.services.rag.factory import get_pipeline
+ pipeline.search_result = {"content": "only-content", "provider": "x"}
+ result = await service.search(query="q", kb_name="kb")
+ assert result["answer"] == "only-content"
+ assert result["content"] == "only-content"
+ assert result["query"] == "q"
- with pytest.raises(ValueError, match="Unknown pipeline"):
- get_pipeline("nonexistent")
+ pipeline.search_result = {"answer": "only-answer", "provider": "x"}
+ result = await service.search(query="q2", kb_name="kb")
+ assert result["content"] == "only-answer"
+ assert result["answer"] == "only-answer"
@pytest.mark.asyncio
-async def test_rag_search_invalid_provider_falls_back_to_kb_provider(
- monkeypatch: pytest.MonkeyPatch,
+async def test_smart_retrieve_aggregates_passages_with_query_hints(
+ fake_service, monkeypatch: pytest.MonkeyPatch,
) -> None:
- """Tool wrapper should defer to KB-resolved provider (llamaindex-only runtime)."""
- from deeptutor.services.rag import service as rag_service_module
- from deeptutor.tools.rag_tool import rag_search
-
- monkeypatch.setattr(
- rag_service_module.RAGService,
- "_get_provider_for_kb",
- lambda self, kb_name: "llamaindex",
+ service, pipeline = fake_service
+ pipeline.search_result = {"answer": "PASSAGE", "content": "PASSAGE", "provider": "x"}
+
+ async def _fake_aggregate(_self, _ctx, passages):
+ return "AGG:" + "|".join(passages)
+
+ monkeypatch.setattr(RAGService, "_aggregate", _fake_aggregate, raising=True)
+
+ out = await service.smart_retrieve(
+ context="anything",
+ kb_name="kb",
+ query_hints=["q1", "q2"],
)
+ assert out["answer"].startswith("AGG:")
+ assert out["answer"].count("PASSAGE") == 2
+ assert len(out["sources"]) == 2
+ queries = [c["query"] for c in pipeline.calls if c["op"] == "search"]
+ assert queries == ["q1", "q2"]
+
- result = await rag_search(
- query="hello",
- kb_name="demo",
- provider="nonexistent",
- kb_base_dir=os.getcwd(),
+async def test_smart_retrieve_returns_empty_when_no_passages(
+ fake_service, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service, pipeline = fake_service
+ pipeline.search_result = {"answer": "", "content": "", "provider": "x"}
+
+ out = await service.smart_retrieve(
+ context="anything",
+ kb_name="kb",
+ query_hints=["q"],
)
- assert result["provider"] == "llamaindex"
+ assert out == {"answer": "", "sources": []}
+
+
+async def test_delete_removes_kb_directory_when_pipeline_lacks_delete(tmp_path) -> None:
+ """Fallback path: delete the KB dir directly if the pipeline does not implement delete."""
+ kb_dir = tmp_path / "demo"
+ (kb_dir / "raw").mkdir(parents=True)
+ (kb_dir / "raw" / "f.txt").write_text("hi")
+
+ class _NoDeletePipeline:
+ async def initialize(self, *a, **k):
+ return True
+
+ async def search(self, *a, **k):
+ return {}
+
+ service = RAGService(kb_base_dir=str(tmp_path))
+ service._pipeline = _NoDeletePipeline() # type: ignore[attr-defined]
+
+ assert await service.delete(kb_name="demo") is True
+ assert not kb_dir.exists()
diff --git a/tests/services/tutorbot/test_channel_secrets.py b/tests/services/tutorbot/test_channel_secrets.py
new file mode 100644
index 000000000..4fe6946f2
--- /dev/null
+++ b/tests/services/tutorbot/test_channel_secrets.py
@@ -0,0 +1,223 @@
+"""Unit tests for channel-secret handling in the TutorBot manager layer.
+
+These guard the contract that secret-looking fields (token, password, api_key,
+…) are NEVER serialised into responses unless the caller explicitly opts into
+``include_secrets=True``. A regression here would re-introduce the token-leak
+fixed alongside PR #338.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.services.tutorbot.manager import (
+ BotConfig,
+ TutorBotInstance,
+ mask_channel_secrets,
+)
+
+# ---------------------------------------------------------------------------
+# mask_channel_secrets
+# ---------------------------------------------------------------------------
+
+
+class TestMaskChannelSecrets:
+ def test_masks_top_level_token(self):
+ out = mask_channel_secrets({"telegram": {"token": "123:abc"}})
+ assert out["telegram"]["token"] == "***"
+
+ def test_masks_nested_password_in_email_section(self):
+ out = mask_channel_secrets(
+ {
+ "email": {
+ "imap_username": "me",
+ "imap_password": "supersecret",
+ "smtp_password": "another",
+ }
+ }
+ )
+ assert out["email"]["imap_username"] == "me"
+ assert out["email"]["imap_password"] == "***"
+ assert out["email"]["smtp_password"] == "***"
+
+ def test_masks_diverse_secret_keys(self):
+ out = mask_channel_secrets(
+ {
+ "slack": {"bot_token": "xoxb-…", "app_token": "xapp-…"},
+ "matrix": {"access_token": "syt_…"},
+ "feishu": {
+ "app_id": "cli_…",
+ "app_secret": "shh",
+ "encrypt_key": "k",
+ "verification_token": "vt",
+ },
+ "wecom": {"secret": "s"},
+ }
+ )
+ assert out["slack"]["bot_token"] == "***"
+ assert out["slack"]["app_token"] == "***"
+ assert out["matrix"]["access_token"] == "***"
+ assert out["feishu"]["app_id"] == "cli_…" # not a secret hint
+ assert out["feishu"]["app_secret"] == "***"
+ assert out["feishu"]["encrypt_key"] == "***"
+ assert out["feishu"]["verification_token"] == "***"
+ assert out["wecom"]["secret"] == "***"
+
+ def test_preserves_non_string_values(self):
+ out = mask_channel_secrets(
+ {"telegram": {"token": "", "enabled": True, "allow_from": ["1", "2"]}}
+ )
+ # Empty string is left as-is (nothing to hide; helps the UI distinguish
+ # "unset" from "redacted").
+ assert out["telegram"]["token"] == ""
+ assert out["telegram"]["enabled"] is True
+ assert out["telegram"]["allow_from"] == ["1", "2"]
+
+ def test_does_not_mutate_input(self):
+ original = {"telegram": {"token": "abc"}}
+ out = mask_channel_secrets(original)
+ assert original["telegram"]["token"] == "abc"
+ assert out is not original
+
+
+# ---------------------------------------------------------------------------
+# TutorBotInstance.to_dict contract
+# ---------------------------------------------------------------------------
+
+
+def _make_instance() -> TutorBotInstance:
+ return TutorBotInstance(
+ bot_id="b",
+ config=BotConfig(
+ name="bot",
+ channels={
+ "telegram": {"enabled": True, "token": "123:ABC"},
+ "send_progress": True,
+ },
+ ),
+ )
+
+
+class TestToDictDefaultsAreSafe:
+ def test_default_returns_keys_only(self):
+ inst = _make_instance()
+ d = inst.to_dict()
+ assert d["channels"] == ["telegram", "send_progress"] or set(
+ d["channels"]
+ ) == {"telegram", "send_progress"}
+ # last_reload_error is always present for the UI to consume
+ assert "last_reload_error" in d
+ assert d["last_reload_error"] is None
+
+ def test_mask_secrets_returns_full_dict_with_token_masked(self):
+ inst = _make_instance()
+ d = inst.to_dict(mask_secrets=True)
+ assert d["channels"]["telegram"]["enabled"] is True
+ assert d["channels"]["telegram"]["token"] == "***"
+ assert d["channels"]["send_progress"] is True
+
+ def test_include_secrets_returns_raw_token(self):
+ inst = _make_instance()
+ d = inst.to_dict(include_secrets=True)
+ assert d["channels"]["telegram"]["token"] == "123:ABC"
+
+ def test_include_secrets_takes_precedence_over_mask(self):
+ inst = _make_instance()
+ d = inst.to_dict(include_secrets=True, mask_secrets=True)
+ assert d["channels"]["telegram"]["token"] == "123:ABC"
+
+
+# ---------------------------------------------------------------------------
+# reload_lock + last_reload_error wiring
+# ---------------------------------------------------------------------------
+
+
+async def test_reload_lock_serialises_concurrent_calls(monkeypatch):
+ """Two concurrent reload_channels calls must not run their bodies in parallel."""
+ import asyncio
+
+ from deeptutor.services.tutorbot.manager import TutorBotManager
+
+ mgr = TutorBotManager()
+ inst = _make_instance()
+
+ class _FakeBus:
+ pass
+
+ class _FakeAgentLoop:
+ bus = _FakeBus()
+
+ inst.agent_loop = _FakeAgentLoop()
+ # Mark the instance as running by giving it a not-done sentinel task.
+ sentinel = asyncio.create_task(asyncio.sleep(60))
+ inst.tasks = [sentinel]
+ mgr._bots["b"] = inst
+
+ overlap_count = 0
+ max_overlap = 0
+ in_flight = 0
+
+ async def fake_teardown(instance, bot_id):
+ nonlocal in_flight, overlap_count, max_overlap
+ in_flight += 1
+ max_overlap = max(max_overlap, in_flight)
+ overlap_count += 1
+ await asyncio.sleep(0.05)
+ in_flight -= 1
+
+ monkeypatch.setattr(mgr, "_teardown_channel_listeners", fake_teardown)
+ monkeypatch.setattr(
+ mgr, "_build_channel_manager", lambda config, bus, *, bot_id: None
+ )
+
+ try:
+ await asyncio.gather(mgr.reload_channels("b"), mgr.reload_channels("b"))
+ assert overlap_count == 2
+ assert max_overlap == 1, "reload_channels must be serialised per bot"
+ finally:
+ sentinel.cancel()
+ try:
+ await sentinel
+ except asyncio.CancelledError:
+ pass
+
+
+async def test_reload_failure_records_last_reload_error(monkeypatch):
+ import asyncio
+
+ from deeptutor.services.tutorbot.manager import TutorBotManager
+
+ mgr = TutorBotManager()
+ inst = _make_instance()
+
+ class _FakeAgentLoop:
+ bus = object()
+
+ inst.agent_loop = _FakeAgentLoop()
+ sentinel = asyncio.create_task(asyncio.sleep(60))
+ inst.tasks = [sentinel]
+ mgr._bots["b"] = inst
+
+ async def fake_teardown(instance, bot_id):
+ return None
+
+ def boom(*args, **kwargs):
+ raise ValueError("invalid telegram token format")
+
+ monkeypatch.setattr(mgr, "_teardown_channel_listeners", fake_teardown)
+ monkeypatch.setattr(mgr, "_build_channel_manager", boom)
+
+ try:
+ with pytest.raises(ValueError):
+ await mgr.reload_channels("b")
+ assert inst.last_reload_error is not None
+ assert "invalid telegram token format" in inst.last_reload_error
+ assert inst.channel_manager is None
+ finally:
+ sentinel.cancel()
+ try:
+ await sentinel
+ except asyncio.CancelledError:
+ pass
diff --git a/tests/tools/test_rag_tool.py b/tests/tools/test_rag_tool.py
index 4ab2a3c7e..ccd4dc3d6 100644
--- a/tests/tools/test_rag_tool.py
+++ b/tests/tools/test_rag_tool.py
@@ -1,18 +1,14 @@
-"""Tests for RAG tool wrappers and pipeline factory."""
+"""Factory + tool-wrapper layer tests (llamaindex-only)."""
from __future__ import annotations
-import warnings
-
import pytest
from deeptutor.services.rag.factory import (
DEFAULT_PROVIDER,
- LEGACY_PROVIDER_ALIASES,
- has_pipeline,
+ get_pipeline,
list_pipelines,
normalize_provider_name,
- get_pipeline,
)
from deeptutor.tools.rag_tool import (
RAGService,
@@ -21,121 +17,62 @@ from deeptutor.tools.rag_tool import (
)
-# ---------------------------------------------------------------------------
-# normalize_provider_name
-# ---------------------------------------------------------------------------
-
-
class TestNormalizeProviderName:
- def test_default_when_none(self) -> None:
- assert normalize_provider_name(None) == DEFAULT_PROVIDER
-
- def test_default_when_empty(self) -> None:
- assert normalize_provider_name("") == DEFAULT_PROVIDER
-
- def test_strips_whitespace(self) -> None:
- assert normalize_provider_name(" llamaindex ") == "llamaindex"
-
- def test_case_insensitive(self) -> None:
- assert normalize_provider_name("LlamaIndex") == "llamaindex"
+ """`normalize_provider_name` is now a stub: every input collapses to llamaindex."""
- def test_legacy_alias_lightrag(self) -> None:
- assert normalize_provider_name("lightrag") == DEFAULT_PROVIDER
+ @pytest.mark.parametrize(
+ "value",
+ [None, "", " ", "llamaindex", "LlamaIndex", "lightrag", "raganything",
+ "raganything_docling", "totally_unknown_xyz"],
+ )
+ def test_collapses_to_default(self, value) -> None:
+ assert normalize_provider_name(value) == DEFAULT_PROVIDER
- def test_legacy_alias_raganything(self) -> None:
- assert normalize_provider_name("raganything") == DEFAULT_PROVIDER
- def test_unknown_passes_through(self) -> None:
- assert normalize_provider_name("custom_pipeline") == "custom_pipeline"
-
-
-# ---------------------------------------------------------------------------
-# Pipeline registry
-# ---------------------------------------------------------------------------
-
-
-class TestPipelineRegistry:
- def test_has_pipeline_default(self) -> None:
- assert has_pipeline(DEFAULT_PROVIDER) is True
-
- def test_has_pipeline_unknown(self) -> None:
- assert has_pipeline("nonexistent_xyz") is False
-
- def test_has_pipeline_empty(self) -> None:
- assert has_pipeline("") is False
-
- def test_list_pipelines_returns_default(self) -> None:
+class TestPipelineFactory:
+ def test_list_pipelines_only_default(self) -> None:
pipelines = list_pipelines()
assert isinstance(pipelines, list)
- assert len(pipelines) >= 1
- ids = {p["id"] for p in pipelines}
- assert DEFAULT_PROVIDER in ids
-
- def test_get_pipeline_unknown_raises(self) -> None:
- with pytest.raises(ValueError, match="Unknown pipeline"):
- get_pipeline("nonexistent_pipeline_xyz")
-
-
-# ---------------------------------------------------------------------------
-# RAGService class methods
-# ---------------------------------------------------------------------------
-
-
-class TestRAGServiceStaticMethods:
- def test_list_providers(self) -> None:
+ assert {p["id"] for p in pipelines} == {DEFAULT_PROVIDER}
+
+ def test_get_pipeline_returns_singleton(self) -> None:
+ try:
+ first = get_pipeline()
+ second = get_pipeline()
+ except (ValueError, ImportError) as exc:
+ pytest.skip(f"LlamaIndex optional dependency missing: {exc}")
+ assert first is second
+
+ def test_get_pipeline_ignores_provider_name(self) -> None:
+ """The legacy ``name`` argument is silently ignored."""
+ try:
+ a = get_pipeline("llamaindex")
+ b = get_pipeline("lightrag")
+ c = get_pipeline("nonexistent_xyz")
+ except (ValueError, ImportError) as exc:
+ pytest.skip(f"LlamaIndex optional dependency missing: {exc}")
+ assert a is b is c
+
+
+class TestRAGServiceClassHelpers:
+ def test_list_providers_only_default(self) -> None:
providers = RAGService.list_providers()
- assert isinstance(providers, list)
- assert any(p["id"] == DEFAULT_PROVIDER for p in providers)
+ assert {p["id"] for p in providers} == {DEFAULT_PROVIDER}
- def test_has_provider_default(self) -> None:
+ def test_has_provider_default_true(self) -> None:
assert RAGService.has_provider(DEFAULT_PROVIDER) is True
- def test_has_provider_unknown(self) -> None:
+ def test_has_provider_unknown_false(self) -> None:
assert RAGService.has_provider("nonexistent") is False
+ assert RAGService.has_provider("") is False
- def test_get_current_provider_returns_string(self) -> None:
- provider = get_current_provider()
- assert isinstance(provider, str)
- assert len(provider) > 0
-
-
-# ---------------------------------------------------------------------------
-# tool-level wrappers
-# ---------------------------------------------------------------------------
-
-
-class TestToolWrappers:
- def test_get_available_providers(self) -> None:
- providers = get_available_providers()
- assert isinstance(providers, list)
-
-
-# ---------------------------------------------------------------------------
-# Deprecated API surface
-# ---------------------------------------------------------------------------
-
-
-class TestDeprecatedAPI:
- def test_get_plugin_warns(self) -> None:
- from deeptutor.services.rag.factory import get_plugin
-
- with warnings.catch_warnings():
- warnings.simplefilter("error", DeprecationWarning)
- with pytest.raises(DeprecationWarning):
- get_plugin(DEFAULT_PROVIDER)
-
- def test_list_plugins_warns(self) -> None:
- from deeptutor.services.rag.factory import list_plugins
-
- with warnings.catch_warnings():
- warnings.simplefilter("error", DeprecationWarning)
- with pytest.raises(DeprecationWarning):
- list_plugins()
+ def test_get_current_provider_ignores_env(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("RAG_PROVIDER", "lightrag")
+ assert get_current_provider() == DEFAULT_PROVIDER
+ monkeypatch.delenv("RAG_PROVIDER", raising=False)
+ assert get_current_provider() == DEFAULT_PROVIDER
- def test_has_plugin_warns(self) -> None:
- from deeptutor.services.rag.factory import has_plugin
- with warnings.catch_warnings():
- warnings.simplefilter("error", DeprecationWarning)
- with pytest.raises(DeprecationWarning):
- has_plugin(DEFAULT_PROVIDER)
+class TestToolLayerExports:
+ def test_get_available_providers_matches_class_method(self) -> None:
+ assert get_available_providers() == RAGService.list_providers()
diff --git a/web/app/(workspace)/agents/page.tsx b/web/app/(workspace)/agents/page.tsx
index 452e49b33..f05a188fd 100644
--- a/web/app/(workspace)/agents/page.tsx
+++ b/web/app/(workspace)/agents/page.tsx
@@ -34,11 +34,18 @@ interface BotInfo {
name: string;
description: string;
persona: string;
- /** Compact list from `GET /tutorbot`; full dict from `GET /tutorbot/{id}` */
- channels: string[] | Record<string, unknown>;
+ /**
+ * From `GET /tutorbot` (list): channel name keys only — never carries secrets.
+ * The single-bot detail endpoint returns a richer dict; ChannelsTab fetches
+ * it explicitly via `?include_secrets=true` and works with that shape directly,
+ * so this list-shape type is sufficient here.
+ */
+ channels: string[];
model: string | null;
running: boolean;
started_at: string | null;
+ /** Set when a previous PATCH succeeded but `reload_channels` failed. */
+ last_reload_error?: string | null;
}
interface SoulTemplate {
@@ -153,33 +160,240 @@ export default function AgentsPage() {
);
}
-/* ── Channels tab (Telegram + globals) ─────────────────── */
-
-const DEFAULT_TELEGRAM = {
- enabled: false,
- token: "",
- allow_from: [] as string[],
- proxy: "" as string,
- reply_to_message: false,
- group_policy: "mention" as "open" | "mention",
+/* ── Channels tab (schema-driven, all channels) ─────────── */
+
+/**
+ * JSON-Schema fragment subset we actually consume. Pydantic emits richer
+ * shapes (allOf / examples / formats) that we ignore — the form gracefully
+ * falls back to a text input for anything it doesn't recognise.
+ */
+type JsonSchema = {
+ type?: string | string[];
+ title?: string;
+ description?: string;
+ default?: unknown;
+ enum?: unknown[];
+ properties?: Record<string, JsonSchema>;
+ items?: JsonSchema;
+ anyOf?: JsonSchema[];
};
-function normalizeChannelsDict(raw: Record<string, unknown> | undefined): Record<string, unknown> {
- const r = { ...(raw ?? {}) };
- const tg = (r.telegram as Record<string, unknown> | undefined) ?? {};
- const allowRaw = tg.allow_from;
- const allow_from = Array.isArray(allowRaw) ? allowRaw.map(String) : [];
- return {
- ...r,
- send_progress: r.send_progress !== false,
- send_tool_hints: !!r.send_tool_hints,
- telegram: {
- ...DEFAULT_TELEGRAM,
- ...tg,
- allow_from,
- group_policy: tg.group_policy === "open" ? "open" : "mention",
- },
- };
+interface ChannelSchemaEntry {
+ name: string;
+ display_name: string;
+ default_config: Record<string, unknown>;
+ secret_fields: string[];
+ json_schema: JsonSchema;
+}
+
+interface ChannelsSchemaResponse {
+ channels: Record<string, ChannelSchemaEntry>;
+ global: { json_schema: JsonSchema; secret_fields: string[] };
+}
+
+/** Pick the first non-null variant of an `anyOf` and merge its meta. */
+function resolveSchemaVariant(s: JsonSchema): JsonSchema {
+ if (!s.anyOf) return s;
+ const first = s.anyOf.find((v) => v.type !== "null") ?? s.anyOf[0];
+ return { ...first, title: s.title ?? first.title, description: s.description ?? first.description };
+}
+
+/** True iff this schema's value can be `null` (e.g. `Optional[str]`). */
+function isNullable(s: JsonSchema): boolean {
+ if (Array.isArray(s.type) && s.type.includes("null")) return true;
+ if (s.anyOf?.some((v) => v.type === "null")) return true;
+ return false;
+}
+
+/** Default value for a property when the live config doesn't set it. */
+function defaultFor(s: JsonSchema): unknown {
+ if (s.default !== undefined) return s.default;
+ const v = resolveSchemaVariant(s);
+ switch (v.type) {
+ case "boolean": return false;
+ case "integer":
+ case "number": return 0;
+ case "array": return [];
+ case "object": return {};
+ case "string":
+ default: return "";
+ }
+}
+
+/** Title-case a snake_case key when no `title` is provided. */
+function humaniseKey(k: string): string {
+ return k.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
+}
+
+/** Generic field renderer — recursive for nested objects. */
+function SchemaField({
+ fieldKey,
+ schema,
+ value,
+ onChange,
+ secretFields,
+ path,
+ showSecretFor,
+ toggleSecret,
+}: {
+ fieldKey: string;
+ schema: JsonSchema;
+ value: unknown;
+ onChange: (next: unknown) => void;
+ secretFields: Set<string>;
+ path: string;
+ showSecretFor: Set<string>;
+ toggleSecret: (path: string) => void;
+}) {
+ const v = resolveSchemaVariant(schema);
+ const label = schema.title || v.title || humaniseKey(fieldKey);
+ const description = schema.description || v.description;
+ const isSecret = secretFields.has(path);
+ const enumValues = (v.enum ?? schema.enum) as unknown[] | undefined;
+
+ // Boolean → checkbox row (label inline).
+ if (v.type === "boolean") {
+ return (
+ <label className="flex items-start gap-2 text-[13px]">
+ <input
+ type="checkbox"
+ checked={!!value}
+ onChange={(e) => onChange(e.target.checked)}
+ className="mt-0.5"
+ />
+ <span>
+ {label}
+ {description && (
+ <span className="ml-1 text-[11px] text-[var(--muted-foreground)]">— {description}</span>
+ )}
+ </span>
+ </label>
+ );
+ }
+
+ // Enum / Literal → select.
+ if (Array.isArray(enumValues) && enumValues.length > 0) {
+ return (
+ <div>
+ <FieldLabel label={label} description={description} />
+ <select
+ value={String(value ?? "")}
+ onChange={(e) => onChange(e.target.value)}
+ className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] outline-none focus:border-[var(--ring)]"
+ >
+ {enumValues.map((opt) => (
+ <option key={String(opt)} value={String(opt)}>{String(opt)}</option>
+ ))}
+ </select>
+ </div>
+ );
+ }
+
+ // Array of strings → textarea (one per line). For non-string arrays we
+ // fall through to JSON editing below.
+ if (v.type === "array" && (v.items?.type === "string" || !v.items)) {
+ const lines = Array.isArray(value) ? (value as unknown[]).map(String) : [];
+ return (
+ <div>
+ <FieldLabel label={label} description={description ?? "One value per line"} />
+ <textarea
+ value={lines.join("\n")}
+ onChange={(e) =>
+ onChange(e.target.value.split("\n").map((s) => s.trim()).filter(Boolean))
+ }
+ rows={Math.max(3, Math.min(8, lines.length + 1))}
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] outline-none focus:border-[var(--ring)]"
+ />
+ </div>
+ );
+ }
+
+ // Nested object → recursive fieldset.
+ if (v.type === "object" && v.properties) {
+ const obj = (value && typeof value === "object" ? value : {}) as Record<string, unknown>;
+ return (
+ <fieldset className="rounded-lg border border-[var(--border)]/60 px-3 py-2.5 space-y-2.5">
+ <legend className="px-1 text-[12px] font-medium text-[var(--muted-foreground)]">{label}</legend>
+ {description && <p className="text-[11px] text-[var(--muted-foreground)]">{description}</p>}
+ {Object.entries(v.properties).map(([k, child]) => (
+ <SchemaField
+ key={k}
+ fieldKey={k}
+ schema={child}
+ value={obj[k] ?? defaultFor(child)}
+ onChange={(next) => onChange({ ...obj, [k]: next })}
+ secretFields={secretFields}
+ path={path ? `${path}.${k}` : k}
+ showSecretFor={showSecretFor}
+ toggleSecret={toggleSecret}
+ />
+ ))}
+ </fieldset>
+ );
+ }
+
+ // Integer/number → number input.
+ if (v.type === "integer" || v.type === "number") {
+ return (
+ <div>
+ <FieldLabel label={label} description={description} />
+ <input
+ type="number"
+ value={typeof value === "number" ? value : ""}
+ onChange={(e) => {
+ const raw = e.target.value;
+ if (raw === "") onChange(isNullable(schema) ? null : 0);
+ else onChange(v.type === "integer" ? parseInt(raw, 10) : parseFloat(raw));
+ }}
+ className="w-40 rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] outline-none focus:border-[var(--ring)]"
+ />
+ </div>
+ );
+ }
+
+ // Default: string input (with secret reveal handling).
+ const reveal = showSecretFor.has(path);
+ const strVal = value == null ? "" : String(value);
+ return (
+ <div>
+ <FieldLabel label={label} description={description} />
+ <div className="relative">
+ <input
+ type={isSecret && !reveal ? "password" : "text"}
+ autoComplete={isSecret ? "new-password" : "off"}
+ spellCheck={!isSecret}
+ value={strVal}
+ onChange={(e) => {
+ const next = e.target.value;
+ // Empty optional strings persist as null (matches Pydantic's
+ // `Optional[str]` default and avoids "" sneaking past validators).
+ onChange(next === "" && isNullable(schema) ? null : next);
+ }}
+ className={`w-full rounded-lg border border-[var(--border)] bg-transparent py-2 pl-3 ${isSecret ? "pr-10 font-mono" : "pr-3"} text-[13px] outline-none focus:border-[var(--ring)]`}
+ />
+ {isSecret && (
+ <button
+ type="button"
+ onClick={() => toggleSecret(path)}
+ className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ aria-label={reveal ? "Hide secret" : "Show secret"}
+ title={reveal ? "Hide secret" : "Show secret"}
+ >
+ {reveal ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function FieldLabel({ label, description }: { label: string; description?: string }) {
+ return (
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
+ {label}
+ {description && <span className="ml-1 font-normal opacity-70">— {description}</span>}
+ </label>
+ );
}
function ChannelsTab({
@@ -195,27 +409,56 @@ function ChannelsTab({
}) {
const { t } = useTranslation();
const [selectedBot, setSelectedBot] = useState("");
+ const [schemaCatalog, setSchemaCatalog] = useState<ChannelsSchemaResponse | null>(null);
const [channels, setChannels] = useState<Record<string, unknown>>({});
+ const [activeChannel, setActiveChannel] = useState<string | null>(null);
+ const [reloadError, setReloadError] = useState<string | null>(null);
const [loadingDetail, setLoadingDetail] = useState(false);
const [saving, setSaving] = useState(false);
- const [showToken, setShowToken] = useState(false);
+ /** dot-paths of secrets the user has explicitly toggled to plaintext. */
+ const [revealed, setRevealed] = useState<Set<string>>(new Set());
+
+ // One-time fetch of the channel schema catalog. Cheap and never changes
+ // at runtime (channels are discovered at process start).
+ useEffect(() => {
+ void (async () => {
+ try {
+ const res = await fetch(apiUrl("/api/v1/tutorbot/channels/schema"));
+ if (res.ok) setSchemaCatalog(await res.json());
+ } catch { /* leave catalog null → renders fallback message */ }
+ })();
+ }, []);
useEffect(() => {
if (bots.length > 0 && !selectedBot) setSelectedBot(bots[0].bot_id);
}, [bots, selectedBot]);
useEffect(() => {
- setShowToken(false);
+ setRevealed(new Set());
+ setReloadError(null);
}, [selectedBot]);
const loadDetail = useCallback(async (bid: string) => {
if (!bid) return;
setLoadingDetail(true);
try {
- const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}`));
+ // Edit form needs raw secrets to populate fields. Default GET masks them.
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}?include_secrets=true`));
if (!res.ok) return;
const data = await res.json();
- setChannels(normalizeChannelsDict(data.channels as Record<string, unknown> | undefined));
+ const raw = (data.channels ?? {}) as Record<string, unknown>;
+ // Surface globals as-is; per-channel dicts are passed straight to the
+ // SchemaForm which handles per-field defaults from the JSON schema.
+ setChannels({
+ send_progress: raw.send_progress !== false,
+ send_tool_hints: !!raw.send_tool_hints,
+ ...Object.fromEntries(
+ Object.entries(raw).filter(([k]) => k !== "send_progress" && k !== "send_tool_hints"),
+ ),
+ });
+ setReloadError(
+ typeof data.last_reload_error === "string" ? data.last_reload_error : null,
+ );
} finally {
setLoadingDetail(false);
}
@@ -225,32 +468,30 @@ function ChannelsTab({
if (selectedBot) void loadDetail(selectedBot);
}, [selectedBot, loadDetail]);
- const tg = (channels.telegram as typeof DEFAULT_TELEGRAM) ?? DEFAULT_TELEGRAM;
-
- const setTg = (patch: Partial<typeof DEFAULT_TELEGRAM>) => {
- setChannels((prev) => ({
- ...prev,
- telegram: { ...DEFAULT_TELEGRAM, ...(prev.telegram as object), ...patch },
- }));
- };
+ // Pick a sensible default active channel: prefer one already enabled,
+ // otherwise the first channel in the catalog.
+ useEffect(() => {
+ if (activeChannel || !schemaCatalog) return;
+ const names = Object.keys(schemaCatalog.channels);
+ const enabled = names.find((n) => {
+ const cfg = channels[n];
+ return cfg && typeof cfg === "object" && (cfg as Record<string, unknown>).enabled === true;
+ });
+ setActiveChannel(enabled ?? names[0] ?? null);
+ }, [schemaCatalog, channels, activeChannel]);
+
+ const toggleSecret = useCallback((path: string) => {
+ setRevealed((prev) => {
+ const next = new Set(prev);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ return next;
+ });
+ }, []);
- const buildPayload = (): Record<string, unknown> => {
- const allow_from = Array.isArray(tg.allow_from)
- ? tg.allow_from.map(String)
- : [];
- const proxyVal = typeof tg.proxy === "string" && tg.proxy.trim() ? tg.proxy.trim() : null;
- const next: Record<string, unknown> = { ...channels };
- next.send_progress = !!channels.send_progress;
- next.send_tool_hints = !!channels.send_tool_hints;
- next.telegram = {
- enabled: !!tg.enabled,
- token: String(tg.token ?? ""),
- allow_from,
- proxy: proxyVal,
- reply_to_message: !!tg.reply_to_message,
- group_policy: tg.group_policy === "open" ? "open" : "mention",
- };
- return next;
+ const setActiveChannelConfig = (next: unknown) => {
+ if (!activeChannel) return;
+ setChannels((prev) => ({ ...prev, [activeChannel]: next }));
};
const save = async () => {
@@ -260,15 +501,24 @@ function ChannelsTab({
const res = await fetch(apiUrl(`/api/v1/tutorbot/${selectedBot}`), {
method: "PATCH",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ channels: buildPayload() }),
+ body: JSON.stringify({ channels }),
});
if (res.ok) {
onToast(t("Channels saved"));
- await onReload();
- await loadDetail(selectedBot);
+ await Promise.all([onReload(), loadDetail(selectedBot)]);
+ } else if (res.status === 422) {
+ const err = (await res.json().catch(() => ({}))) as {
+ detail?: { message?: string; errors?: unknown } | string;
+ };
+ const detail = err.detail;
+ const msg =
+ typeof detail === "string"
+ ? detail
+ : detail?.message ?? t("Invalid channel configuration");
+ onToast(msg);
} else {
- const err = await res.json().catch(() => ({}));
- onToast((err as { detail?: string }).detail ?? t("Save failed"));
+ const err = (await res.json().catch(() => ({}))) as { detail?: string };
+ onToast(err.detail ?? t("Save failed"));
}
} finally {
setSaving(false);
@@ -294,6 +544,18 @@ function ChannelsTab({
);
}
+ const channelEntries = schemaCatalog
+ ? Object.entries(schemaCatalog.channels).sort(([, a], [, b]) =>
+ a.display_name.localeCompare(b.display_name),
+ )
+ : [];
+ const activeEntry = activeChannel ? schemaCatalog?.channels[activeChannel] : undefined;
+ const activeValue =
+ activeChannel && channels[activeChannel] && typeof channels[activeChannel] === "object"
+ ? (channels[activeChannel] as Record<string, unknown>)
+ : (activeEntry?.default_config ?? {});
+ const activeSecretSet = new Set(activeEntry?.secret_fields ?? []);
+
return (
<div className="space-y-5">
<div className="flex flex-wrap items-center gap-3">
@@ -320,12 +582,23 @@ function ChannelsTab({
</button>
</div>
- {loadingDetail ? (
+ {reloadError && (
+ <div className="rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-700 dark:text-amber-300">
+ <strong className="font-medium">{t("Channel listeners failed to restart:")}</strong>{" "}
+ <span className="font-mono">{reloadError}</span>{" "}
+ <span className="opacity-80">
+ {t("Config is saved on disk; stop and start the bot to apply.")}
+ </span>
+ </div>
+ )}
+
+ {loadingDetail || !schemaCatalog ? (
<div className="flex justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
</div>
) : (
<>
+ {/* Globals (Delivery) */}
<div className="rounded-xl border border-[var(--border)] p-4 space-y-3">
<h3 className="text-[13px] font-medium text-[var(--foreground)]">{t("Delivery")}</h3>
<label className="flex items-center gap-2 text-[13px]">
@@ -346,78 +619,74 @@ function ChannelsTab({
</label>
</div>
- <div className="rounded-xl border border-[var(--border)] p-4 space-y-3">
- <h3 className="text-[13px] font-medium text-[var(--foreground)]">{t("Telegram")}</h3>
- <label className="flex items-center gap-2 text-[13px]">
- <input
- type="checkbox"
- checked={!!tg.enabled}
- onChange={(e) => setTg({ enabled: e.target.checked })}
- />
- {t("Enabled")}
- </label>
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Bot token")}</label>
- <div className="relative">
- <input
- type={showToken ? "text" : "password"}
- autoComplete="off"
- value={tg.token}
- onChange={(e) => setTg({ token: e.target.value })}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent py-2 pl-3 pr-10 font-mono text-[13px] outline-none focus:border-[var(--ring)]"
- />
- <button
- type="button"
- onClick={() => setShowToken((v) => !v)}
- className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- aria-label={showToken ? t("Hide token") : t("Show token")}
- title={showToken ? t("Hide token") : t("Show token")}
- >
- {showToken ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
- </button>
- </div>
- </div>
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Allowed user IDs (one per line)")}</label>
- <textarea
- value={tg.allow_from.join("\n")}
- onChange={(e) =>
- setTg({
- allow_from: e.target.value.split("\n").map((s) => s.trim()).filter(Boolean),
- })
- }
- rows={4}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] outline-none focus:border-[var(--ring)]"
- />
- </div>
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Proxy URL")} <span className="font-normal opacity-60">{t("(optional)")}</span></label>
- <input
- value={tg.proxy ?? ""}
- onChange={(e) => setTg({ proxy: e.target.value })}
- placeholder="http://127.0.0.1:7890"
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] outline-none focus:border-[var(--ring)]"
- />
- </div>
- <label className="flex items-center gap-2 text-[13px]">
- <input
- type="checkbox"
- checked={!!tg.reply_to_message}
- onChange={(e) => setTg({ reply_to_message: e.target.checked })}
- />
- {t("Reply to the user message (vs new message)")}
- </label>
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Group policy")}</label>
- <select
- value={tg.group_policy}
- onChange={(e) => setTg({ group_policy: e.target.value as "open" | "mention" })}
- className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] outline-none focus:border-[var(--ring)]"
- >
- <option value="mention">{t("Mention only")}</option>
- <option value="open">{t("Open (all messages)")}</option>
- </select>
- </div>
+ {/* Channel master-detail */}
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-[180px_1fr]">
+ <aside className="rounded-xl border border-[var(--border)] p-2 h-fit">
+ <ul className="space-y-0.5">
+ {channelEntries.map(([name, entry]) => {
+ const cfg = channels[name] as Record<string, unknown> | undefined;
+ const enabled = cfg?.enabled === true;
+ const isActive = activeChannel === name;
+ return (
+ <li key={name}>
+ <button
+ type="button"
+ onClick={() => setActiveChannel(name)}
+ className={`group flex w-full items-center justify-between rounded-md px-2.5 py-1.5 text-left text-[13px] transition-colors ${
+ isActive
+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ <span className="truncate">{entry.display_name}</span>
+ {enabled && (
+ <span
+ aria-label={t("Enabled")}
+ title={t("Enabled")}
+ className="ml-2 h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"
+ />
+ )}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </aside>
+
+ <section className="rounded-xl border border-[var(--border)] p-4 space-y-3">
+ {!activeEntry ? (
+ <p className="text-[13px] text-[var(--muted-foreground)]">{t("Select a channel.")}</p>
+ ) : (
+ <>
+ <div className="flex items-baseline justify-between">
+ <h3 className="text-[14px] font-medium text-[var(--foreground)]">
+ {activeEntry.display_name}
+ </h3>
+ <code className="text-[11px] text-[var(--muted-foreground)]">{activeEntry.name}</code>
+ </div>
+ {activeEntry.json_schema.description && (
+ <p className="text-[11px] text-[var(--muted-foreground)]">
+ {activeEntry.json_schema.description}
+ </p>
+ )}
+ {Object.entries(activeEntry.json_schema.properties ?? {}).map(([k, child]) => (
+ <SchemaField
+ key={k}
+ fieldKey={k}
+ schema={child}
+ value={activeValue[k] ?? defaultFor(child)}
+ onChange={(next) =>
+ setActiveChannelConfig({ ...activeValue, [k]: next })
+ }
+ secretFields={activeSecretSet}
+ path={k}
+ showSecretFor={revealed}
+ toggleSecret={toggleSecret}
+ />
+ ))}
+ </>
+ )}
+ </section>
</div>
</>
)}