Merge branch 'dev' into claude/deeptutor-model-config-efe083

This commit is contained in:
Bingxi Zhao (Frank)
2026-08-29 21:52:46 +08:00
120 changed files with 6672 additions and 2351 deletions
+4
View File
@@ -170,6 +170,10 @@ jobs:
pip install -r requirements/partners.txt
pip install pytest pytest-asyncio
- name: Install optional LightRAG SDK
if: matrix.python-version == '3.12'
run: pip install "lightrag-hku==1.5.7rc2"
- name: Create minimal runtime config
run: |
mkdir -p data/user/settings
+2
View File
@@ -26,6 +26,8 @@ deeptutor/services/rag/eg_only_for_analysis/
*.synctex.gz
*.pdf
!demo/*.pdf
!tests/fixtures/lightrag_bridge/original.pdf
!tests/fixtures/lightrag_bridge/mineru-v2-current/*_origin.pdf
# ============================================
# Python Related
+9 -1
View File
@@ -277,9 +277,11 @@ python -m pip install --upgrade pip
</details>
<details>
<summary><b>Optional install extras</b> — dev / partners / matrix / math-animator</summary>
<summary><b>Optional install extras</b> — RAG engines / dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[rag-lightrag]" # Built-in LightRAG engine (exact supported SDK)
pip install -e ".[graphrag]" # Microsoft GraphRAG engine
pip install -e ".[dev]" # tests/lint tools
pip install -e ".[partners]" # Partner IM channel SDKs
pip install -e ".[matrix]" # Matrix channel without E2EE/libolm
@@ -602,6 +604,8 @@ Knowledge bases are the document collections behind RAG — they ground Chat tur
Creating a KB, you either **create new** (upload documents and build a fresh index) or **link existing** (reuse an index built elsewhere, read in place with no re-index). A KB can also track **GitHub repositories** (repo, branch, glob) or **documentation-site URLs** (bounded crawl depth and page count); on-demand sync hash-diffs added, changed, and removed content so followed documentation stays current without re-uploading. Re-indexing writes a new flat `version-N` directory and keeps prior ones, so a working index is never destroyed mid-rebuild. A single document can be removed even from an **error**-state base — dropping a file that failed to parse without a full delete-and-rebuild. Document parsing — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM, or LiteParse — is chosen in **Settings → Knowledge Base**, with local model downloads off by default. Docling can also run in **remote** mode against a Docling Serve server (no local install or models needed), configured via **Settings → Document Parsing** (`mode=remote`, a server base URL, and an optional API key) or the `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` environment variables. Tika is remote-only and points at an Apache Tika server (`TIKA_SERVER_URL`). The CLI mirrors the lifecycle with `list/info/create/add/search/set-default/delete`, source add/remove commands, `list-sources`, and `sync`.
The built-in LightRAG engine is installed with `pip install 'deeptutor[rag-lightrag]'`. That extra contains the supported LightRAG SDK but does not install MinerU. Choose MinerU independently in Document Parsing and either configure its cloud mode or install its local CLI when structured PDF parsing is wanted; text-only and the other parsing engines do not require MinerU.
</details>
<details>
@@ -829,8 +833,12 @@ Because DeepTutor speaks the open Agent-Skills format, **[ClawHub](https://clawh
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
deeptutor skill install clawhub:udiedrichsen/stock-analysis
```
When several publishers share the same slug, search shows each publisher and a
fully scoped install ref (`clawhub:<ownerHandle>/<slug>`).
Add more registries in `settings/skill_hubs.json`: a `type: "clawhub"` entry points at any compatible HTTP API (EduHub and ClawHub both speak it), `type: "command"` wraps whatever fetch CLI a registry ships, and `"default"` chooses the hub used for bare slugs. All of them feed the same import gate.
</details>
+39 -4
View File
@@ -164,6 +164,7 @@ class LLMCallResult:
visible_text: str = ""
tool_calls: list[dict[str, Any]] = field(default_factory=list)
finish_reason: str = ""
reasoning_content: str = ""
deferred_chunk_metadata: dict[str, Any] | None = None
deferred_completion_metadata: dict[str, Any] | None = None
@@ -367,7 +368,11 @@ class AgentLoop:
if result.visible_text:
continued_answer_parts.append(result.visible_text)
if result.text:
messages.append({"role": "assistant", "content": result.text})
self._append_assistant_turn(
messages,
content=result.text,
reasoning_content=result.reasoning_content,
)
self._append_loop_instruction(
messages,
self.pipeline._t(
@@ -400,7 +405,11 @@ class AgentLoop:
metadata={"trace_kind": "warning"},
)
if result.text:
messages.append({"role": "assistant", "content": result.text})
self._append_assistant_turn(
messages,
content=result.text,
reasoning_content=result.reasoning_content,
)
self._append_loop_instruction(
messages,
self.pipeline._t(
@@ -423,7 +432,11 @@ class AgentLoop:
if not finish_redirect_used:
finish_redirect_used = True
if result.text:
messages.append({"role": "assistant", "content": result.text})
self._append_assistant_turn(
messages,
content=result.text,
reasoning_content=result.reasoning_content,
)
self._append_loop_instruction(messages, finish_redirect)
continue
await self.stream.progress(
@@ -448,7 +461,13 @@ class AgentLoop:
)
await self._release_deferred_output(result)
messages.append(assistant_message_with_tool_calls(result.text, result.tool_calls))
messages.append(
assistant_message_with_tool_calls(
result.text,
result.tool_calls,
reasoning_content=result.reasoning_content or None,
)
)
dispatch = await self.pipeline._dispatch_tool_calls(
tool_calls=result.tool_calls,
context=self.context,
@@ -517,6 +536,19 @@ class AgentLoop:
return
messages.append({"role": "user", "content": instruction})
@staticmethod
def _append_assistant_turn(
messages: list[dict[str, Any]],
*,
content: str,
reasoning_content: str = "",
) -> None:
"""Append an assistant row, replaying thinking-mode reasoning when present."""
message: dict[str, Any] = {"role": "assistant", "content": content}
if reasoning_content:
message["reasoning_content"] = reasoning_content
messages.append(message)
def _fold_context_checkpoint(
self,
*,
@@ -741,6 +773,7 @@ class AgentLoop:
# once, only after a successful attempt.
usage_seen: Any = None
text_parts: list[str] = []
reasoning_parts: list[str] = []
tool_acc = ToolCallAccumulator()
output_chars = 0
finish_reason = ""
@@ -794,6 +827,7 @@ class AgentLoop:
if reasoning_text:
output_chars += len(reasoning_text)
output_emitted = True
reasoning_parts.append(reasoning_text)
await self.stream.thinking(
reasoning_text, source="chat", stage=stage, metadata=chunk_meta
)
@@ -978,6 +1012,7 @@ class AgentLoop:
visible_text="".join(visible_text_parts),
tool_calls=tool_calls,
finish_reason=finish_reason,
reasoning_content="".join(reasoning_parts),
deferred_chunk_metadata=chunk_meta if defer_visible_output else None,
deferred_completion_metadata=(
completion_event_metadata if defer_visible_output else None
@@ -70,17 +70,19 @@ loop:
That tool-less reply is shown to the user as the answer and ends the
loop, so write it for the reader: use concise Markdown and clear teaching
language, do not mention these internal mechanics or repeat your working
notes verbatim, and include any artifact URLs (e.g. from exec) you
collected. Build the answer on the conversation above — the gathered
notes verbatim, and refer to generated artifacts exactly as the tool result
lists them. Build the answer on the conversation above — the gathered
evidence, memory, persona, and attached sources.
If a skill listed in the Skills block matches the task, call read_skill
before attempting that workflow, then follow the skill instructions.
When a skill or request involves scripts or downloadable files (PDFs,
images, spreadsheets, archives), save them in the turn workspace and run
commands with exec; the exec result lists Generated artifacts with URLs —
cite those URLs in the final answer. If an extended tool is listed but
not loaded, call load_tools first with the exact tool name.
When a skill or request involves Python scripts or downloadable files
(PDFs, images, spreadsheets, archives), pass complete source to
code_execution and save outputs in the turn workspace. Use exec only for
genuinely shell-only commands; never embed Python source in `python -c`
or a heredoc. The tool result lists generated artifacts explicitly —
without that list, do not claim a file was created. If an extended tool is
listed but not loaded, call load_tools first with the exact tool name.
Tool names, parameter names, source ids, knowledge-base names, notebook
ids, and skill names must be copied verbatim from the prompt blocks or
@@ -50,12 +50,14 @@ loop:
当材料已经足够——或这个请求根本不需要工具时——就停止调用工具,直接写出面向用户的最终回答。
这条不带工具调用的回复会作为正式答案呈现给用户并结束循环,所以要为读者而写:用简洁 Markdown
和清晰的教学语言,不要提及这些内部机制、也不要逐字复述你的工作笔记,并带上你收集到的 artifact URL
(如 exec 生成的文件)。基于上面的对话——已收集的证据、记忆、persona 和附件来源——作答。
和清晰的教学语言,不要提及这些内部机制、也不要逐字复述你的工作笔记,并按工具结果原样引用生成文件。
基于上面的对话——已收集的证据、记忆、persona 和附件来源——作答。
如果 Skills 区域里有匹配任务的 skill,先调用 read_skill 再执行该工作流,并遵循 skill 的指示。
当 skill 或请求涉及脚本或可下载文件(PDF、图片、表格、压缩包)时,把文件保存在本轮工作区并用 exec 运行命令;
exec 结果会列出带 URL 的 Generated artifacts——在最终回答里引用这些 URL。
当 skill 或请求涉及 Python 脚本或可下载文件(PDF、图片、表格、压缩包)时,把完整源码传给
code_execution,并把输出保存到本轮工作区。exec 只用于真正必须使用 shell 的命令;
绝不要把 Python 源码嵌进 `python -c` 或 heredoc。工具结果会明确列出生成文件;
没有这个清单就不要宣称已创建文件。
如果 Extended Tools 里列出的工具尚未加载,先用精确工具名调用 load_tools。
工具名、参数名、source id、知识库名、笔记本 id 和 skill 名必须从提示词块或工具 schema 中逐字复制,
+17 -1
View File
@@ -42,10 +42,26 @@ class DeepQuestionCapability(BaseCapability):
llm_config = get_llm_config()
kb_name = context.knowledge_bases[0] if context.knowledge_bases else None
turn_id = str(context.metadata.get("turn_id", "") or context.session_id or "deep-question")
output_dir = get_path_service().get_task_workspace("deep_question", turn_id)
i18n = StatusI18n(self.name, context.language, module="question")
overrides = context.config_overrides
mode = str(overrides.get("mode", "custom") or "custom").strip().lower()
topic = str(overrides.get("topic") or context.user_message or "").strip()
# Validate user-fixable input before allocating a workspace or invoking
# any provider/parser. This keeps an empty custom request from
# surfacing a low-level filesystem error such as ``Operation not
# permitted``.
if mode == "custom" and not topic:
await stream.error(
i18n.t(
"topic_required",
"Please provide a topic before generating questions.",
),
source=self.name,
metadata={"code": "topic_required", "retryable": True},
)
return
output_dir = get_path_service().get_task_workspace("deep_question", turn_id)
followup_question_context = context.metadata.get("question_followup_context", {}) or {}
if isinstance(followup_question_context, dict) and followup_question_context.get(
"question"
+3
View File
@@ -59,6 +59,7 @@ class CreateBookRequest(BaseModel):
question_categories: list[int] = Field(default_factory=list)
question_entries: list[int] = Field(default_factory=list)
language: str = Field(default="en")
fallback_language: str = Field(default="en")
depth: str = Field(default="standard")
@@ -682,6 +683,7 @@ async def create_book(req: CreateBookRequest) -> dict[str, Any]:
question_categories=req.question_categories,
question_entries=req.question_entries,
language=req.language,
fallback_language=req.fallback_language,
depth=req.depth,
)
except Exception as exc: # noqa: BLE001
@@ -1330,6 +1332,7 @@ async def book_websocket(ws: WebSocket) -> None:
],
question_entries=[int(e) for e in (data.get("question_entries") or [])],
language=str(data.get("language") or "en"),
fallback_language=str(data.get("fallback_language") or "en"),
depth=str(data.get("depth") or "standard"),
stream=creation_bus,
)
+38 -2
View File
@@ -9,8 +9,10 @@ from fastapi.responses import FileResponse
from deeptutor.api.routers.auth import require_auth
from deeptutor.multi_user.context import get_current_user_or_none
from deeptutor.multi_user.partner_access import visible_partners
from deeptutor.multi_user.paths import get_path_service_for_scope
from deeptutor.services.auth import TokenPayload
from deeptutor.services.partners.scope import partner_scope
from deeptutor.services.path_service import PathService
router = APIRouter()
@@ -37,11 +39,45 @@ def _resolve_output(path_service: PathService, relative_path: str) -> Path:
return output_path
def _resolve_partner_output(relative_path: str) -> Path | None:
"""Resolve *relative_path* against partner scopes the caller may use.
Partner web chats run inside a synthetic workspace under
``data/partners/<id>/workspace``, so generated files are not beneath the
human caller's own ``data/users/<uid>`` tree. The public artifact URL shape
is still ``/api/outputs/<relative path>``, which means the download surface
has to search the caller's visible partner workspaces when their own
workspace misses (#1012).
The first-party chat flow already scopes the request to one conversation, so
the same relative path colliding across multiple partners is vanishingly
unlikely. Fail closed anyway: only a unique partner match is served.
"""
matches: list[Path] = []
for partner in visible_partners():
partner_id = str(partner.get("partner_id") or "").strip()
if not partner_id:
continue
candidate = get_path_service_for_scope(
partner_scope(partner_id)
).resolve_public_output_path(relative_path)
if candidate is not None:
matches.append(candidate)
if len(matches) > 1:
return None
return matches[0] if matches else None
@router.api_route("/{output_path:path}", methods=["GET", "HEAD"])
async def read_output(
output_path: str,
_auth: TokenPayload | None = Depends(require_auth),
) -> FileResponse:
"""Serve one allowlisted artifact from the authenticated user's workspace."""
path = _resolve_output(_request_path_service(), output_path)
"""Serve one allowlisted artifact from the authenticated user's reach."""
try:
path = _resolve_output(_request_path_service(), output_path)
except HTTPException:
path = _resolve_partner_output(output_path)
if path is None:
raise
return FileResponse(path)
+7
View File
@@ -56,6 +56,7 @@ from .agents.spine_synthesizer import SpineSynthesizer
from .compiler import BookCompiler, CompilerOptions, systemic_failure_reason
from .event_hub import close_book_bus, get_book_bus
from .inputs import IdeationContext, build_book_inputs
from .language import resolve_book_language
from .models import (
Block,
BlockStatus,
@@ -422,12 +423,18 @@ class BookEngine:
question_categories: list[int] | None = None,
question_entries: list[int] | None = None,
language: str = "en",
fallback_language: str = "en",
depth: str = BookDepth.STANDARD.value,
stream: StreamBus | None = None,
) -> tuple[Book, BookProposal]:
"""Capture inputs, run IdeationAgent, persist DRAFT book + proposal."""
bus = stream or StreamBus()
bstream = BookStream(bus)
language = resolve_book_language(
user_intent=user_intent,
requested_language=language,
fallback_language=fallback_language,
)
async with bstream.stage(STAGE_IDEATION):
await bstream.progress("Capturing inputs…", stage=STAGE_IDEATION)
+102
View File
@@ -0,0 +1,102 @@
"""Deterministic language selection for book creation."""
from __future__ import annotations
import re
import unicodedata
from deeptutor.services.prompt.language import normalize_language
_AUTO_LANGUAGE = "auto"
# Only phrased requests are treated as explicit language selection. Merely
# mentioning "Japanese history" must not force a Japanese book.
_LANGUAGE_CUES: tuple[tuple[str, str], ...] = (
("zh-tw", r"(?:繁體中文|正體中文|traditional\s+chinese)"),
("zh", r"(?:用(?:简体中文|中文|汉语)|以(?:中文|汉语)|in\s+chinese|in\s+mandarin)"),
("ja", r"(?:日本語で|用(?:日语|日文)|in\s+japanese)"),
("ko", r"(?:한국어로|用(?:韩语|韓語)|in\s+korean)"),
("ru", r"(?:по-русски|на\s+русском|in\s+russian)"),
("es", r"(?:en\s+español|en\s+espanol|in\s+spanish|castellano|用(?:西班牙语|西班牙文))"),
("fr", r"(?:en\s+français|en\s+francais|in\s+french|用(?:法语|法文))"),
("de", r"(?:auf\s+deutsch|in\s+german|用(?:德语|德文))"),
("pt", r"(?:em\s+português|em\s+portugues|in\s+portuguese|用(?:葡萄牙语|葡萄牙文))"),
("it", r"(?:in\s+italiano|in\s+italian|用(?:意大利语|意大利文))"),
("en", r"(?:in\s+english|英語で|用(?:英语|英文)|en\s+anglais|en\s+inglés)"),
)
_COMPILED_CUES = tuple(
(language, re.compile(pattern, re.IGNORECASE | re.UNICODE))
for language, pattern in _LANGUAGE_CUES
)
def _explicit_language(user_intent: str) -> str | None:
"""Return the last explicit language request in the intent."""
matches: list[tuple[int, str]] = []
for language, pattern in _COMPILED_CUES:
for match in pattern.finditer(user_intent):
matches.append((match.start(), language))
if not matches:
return None
return max(matches, key=lambda item: item[0])[1]
def _script_language(user_intent: str) -> str | None:
"""Infer high-confidence scripts without a language-detection dependency."""
counts = {"latin": 0, "han": 0, "kana": 0, "hangul": 0, "cyrillic": 0}
for char in user_intent:
if not char.isalpha():
continue
script = unicodedata.name(char, "").split(" ", 1)[0]
if script == "LATIN":
counts["latin"] += 1
elif script in {"HIRAGANA", "KATAKANA"}:
counts["kana"] += 1
elif script == "HANGUL":
counts["hangul"] += 1
elif script == "CYRILLIC":
counts["cyrillic"] += 1
elif (
"\u3400" <= char <= "\u4dbf"
or "\u4e00" <= char <= "\u9fff"
or "\uf900" <= char <= "\ufaff"
):
counts["han"] += 1
# Han characters are ambiguous between Chinese and Japanese. Kana resolves
# that ambiguity; Kanji-only Japanese remains intentionally conservative.
if counts["kana"]:
return "ja"
if counts["hangul"] > max(counts["latin"], counts["han"], counts["cyrillic"]):
return "ko"
if counts["cyrillic"] > counts["latin"]:
return "ru"
if counts["han"] > max(counts["latin"], counts["hangul"], counts["cyrillic"]):
return "zh"
return None
def resolve_book_language(
*,
user_intent: str,
requested_language: str | None = "auto",
fallback_language: str | None = "en",
) -> str:
"""Resolve a concrete book language before any generation stage runs.
Explicit selections always win. ``auto`` uses an explicit request cue, then
a high-confidence script signal, then the caller's fallback (normally the
interface language).
"""
requested = normalize_language(requested_language)
fallback = normalize_language(fallback_language)
if requested not in {_AUTO_LANGUAGE, "automatic", "detect"}:
return requested
intent = user_intent or ""
return _explicit_language(intent) or _script_language(intent) or fallback
__all__ = ["resolve_book_language"]
+5 -4
View File
@@ -4,10 +4,11 @@ There is no bespoke state machine here anymore. The chat agent loop IS the
tutor: this capability only marks the turn as mastery mode and resolves the
*initial* active path id, then runs the standard agentic chat pipeline. The
pipeline mounts the mastery tools — the gate tools (``mastery_status`` /
``mastery_quiz`` / ``mastery_grade`` / ``mastery_assess`` / ``mastery_build``)
and the binding tools (``mastery_paths`` / ``mastery_switch`` /
``mastery_leave``), through which the tutor can move the conversation between
paths mid-turn — and injects the tutor playbook; the pure engine in
``mastery_quiz`` / ``mastery_grade`` / ``mastery_skip_question`` /
``mastery_assess`` / ``mastery_build``) and the binding tools
(``mastery_paths`` / ``mastery_switch`` / ``mastery_leave``), through which
the tutor can move the conversation between paths mid-turn — and injects the
tutor playbook; the pure engine in
:mod:`deeptutor.learning` owns the hard, per-type mastery gate and the
spaced-repetition arithmetic.
@@ -7,6 +7,7 @@ Then act on the objective:
- No objectives yet? Design a path from the learner's materials (use `rag` / `read_source` when materials are attached) and call `mastery_build`. Tag each knowledge point: memory (facts), procedure (step-by-step skills), concept (ideas to understand), design (open-ended judgement).
- `probe` (untouched): briefly check whether the learner already knows it before teaching. A test-out is not a silent skip — record its result through the gate (`mastery_assess` for concept / design, `mastery_quiz` + `mastery_grade` for memory / procedure) before advancing. Never move past an objective the engine hasn't marked mastered.
- memory / procedure objectives: register the question + its answer with `mastery_quiz`, then ALWAYS present it with the `ask_user` tool so the learner answers on an interactive card — never write the choices as plain numbered text. For multiple choice, pass every full option body to `mastery_quiz.options` in label order (for example `A: ...`, `B: ...`), give the matching `ask_user` options the short labels A / B / C … with those same bodies as their descriptions, and set the correct label as `mastery_quiz`'s `expected_answer`. Never pass bare labels as `mastery_quiz.options`. If `mastery_status.next.pending_question` exists, reuse its question id, prompt, and option labels/bodies exactly; never regenerate or reorder them. If `pending_interaction.status` is `answered`, immediately call `mastery_grade` with its persisted `learner_answer` and `question_id` instead of asking the learner twice. Otherwise present the pending question with `ask_user`. For open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`, passing the persisted `question_id`. Keep working the same objective until `mastery_grade` reports `mastered: true`. Always pass `explanation` to `mastery_quiz` (why the expected answer is right): it never appears on the card the learner is answering, but it travels with the attempt into their question bank, where it is the only explanation they will have when reviewing the mistake.
- If the learner explicitly asks to abandon the current question (or it is unrecoverably stuck after retrying an `answered` grade), call `mastery_skip_question`, then continue the same objective with a different `mastery_quiz`. A skipped question gives no mastery credit and must never be used to pass a gate.
- concept / design objectives: ask the learner to explain the idea in their own words, judge it, and record the result with `mastery_assess` (`passed: true` only when the explanation truly shows understanding).
- `review`: a spaced-repetition item is due — quiz it again to refresh it.
- `complete`: congratulate the learner and summarise what they have mastered.
@@ -7,6 +7,7 @@
- 还没有任何知识点?根据学习者的材料设计一条路径(材料已挂载时用 `rag` / `read_source`),调用 `mastery_build`。给每个知识点标类型:memory(记忆/事实)、procedure(程序/步骤技能)、concept(概念/需理解)、design(设计/开放判断)。
- `probe`(未触碰):先简短探查学习者是否已经会了再教。"测试通过"不等于直接跳过——仍要用门工具记录结果(concept / design 用 `mastery_assess`,memory / procedure 用 `mastery_quiz` + `mastery_grade`)再推进;绝不要越过引擎尚未标记为"已掌握"的知识点。
- memory / procedure 类:先用 `mastery_quiz` 登记题目与答案,然后**始终用 `ask_user` 工具**把题目呈现成可点选的卡片让学习者作答——绝不要把选项写成纯文字的 1./2./3.。选择题必须把每个选项的完整正文按标签顺序传入 `mastery_quiz.options`(例如 `A:……`、`B:……`),再给 `ask_user` 使用 A / B / C … 短标签,并把相同正文放进对应 description;正确标签设为 `mastery_quiz` 的 `expected_answer`。绝不能只把 A/B/C/D 裸标签传给 `mastery_quiz.options`。如果 `mastery_status.next.pending_question` 存在,必须原样复用其中的题号、题面和选项标签/正文,绝不重新生成或调整顺序。如果 `pending_interaction.status` 是 `answered`,应立即用其中持久化的 `learner_answer` 和 `question_id` 调用 `mastery_grade`,不要让学习者重复作答;否则再用 `ask_user` 展示待答题目。简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改,并传入持久化的 `question_id`。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。每次调用 `mastery_quiz` 都要带上 `explanation`(这个答案为什么对):它不会出现在作答卡片上,但会随作答记录进入学习者的题库,是他们日后复习错题时唯一能看到的解析。
- 如果学习者明确要求放弃当前题目,或重试已提交 (`answered`) 的评分后仍无法恢复,调用 `mastery_skip_question`,然后继续同一知识点并另出一题。被跳过的题目不给任何掌握度,也绝不能用来越过门槛。
- concept / design 类:让学习者用自己的话解释该概念,你来判断,并用 `mastery_assess` 记录结果(只有解释确实体现理解时才 `passed: true`)。
- `review`:有到期的间隔复习项——再考一次以巩固。
- `complete`:祝贺学习者并总结其已掌握的内容。
+157 -20
View File
@@ -18,6 +18,7 @@ from __future__ import annotations
import asyncio
import json
import logging
import re
from typing import TYPE_CHECKING, Any
import uuid
@@ -68,6 +69,7 @@ MASTERY_TOOL_NAMES: tuple[str, ...] = (
"mastery_status",
"mastery_quiz",
"mastery_grade",
"mastery_skip_question",
"mastery_assess",
"mastery_build",
"mastery_paths",
@@ -77,6 +79,12 @@ MASTERY_TOOL_NAMES: tuple[str, ...] = (
_QUESTION_TYPES = ("choice", "short", "open")
_ALLOWED_KP_TYPES = {t.value for t in KnowledgeType}
_BUILD_SHAPE_ERROR = (
"mastery_build could not read any objective. Send modules as "
'\'modules\': [{"name": "<module>", "knowledge_points": '
'[{"name": "<objective>", "type": "memory|procedure|concept|design"}]}] '
"— every knowledge point needs a name of at least two characters."
)
logger = logging.getLogger(__name__)
@@ -814,6 +822,51 @@ class MasteryAssessTool(BaseTool):
return _json_result(payload, meta_key="mastery_assess")
class MasterySkipQuestionTool(BaseTool):
"""Abandon the open question without inventing a graded result."""
def get_definition(self) -> ToolDefinition:
return ToolDefinition(
name="mastery_skip_question",
description=(
"Abandon the currently open mastery question without grading "
"it. This keeps every attempt and mastery level already earned, "
"but gives no credit for the abandoned question. Use it only "
"when the learner explicitly asks to skip this question or the "
"question is unrecoverably stuck; if mastery_status reports an "
"answered interaction, retry mastery_grade first."
),
parameters=[],
)
async def execute(self, **kwargs: Any) -> ToolResult:
path_id = _resolve_path_id(kwargs)
if not path_id:
return _no_path_result()
service = _new_service()
if _load_path(service, path_id) is None:
return _no_built_path_result("mastery_skip_question")
interaction = service.store.get_active_interaction(path_id)
progress, skipped = service.abandon_active_question(path_id)
payload = {
"status": "skipped" if skipped else "no_pending_question",
"skipped": skipped,
"path_revision": progress.version,
"question_id": interaction.interaction_id if interaction is not None else "",
"next": next_objective(progress).to_dict(),
"instruction": (
"The question was abandoned without an attempt or mastery credit. "
"Continue the objective from mastery_status.next and register a "
"different question with mastery_quiz."
if skipped
else "No question was open; follow mastery_status.next."
),
}
return _json_result(payload, meta_key="mastery_skip_question")
class MasteryBuildTool(BaseTool):
"""Create / extend the skill map from objectives the tutor designed."""
@@ -892,7 +945,12 @@ class MasteryBuildTool(BaseTool):
mode = "replace"
service = _new_service()
new_modules, error = _parse_modules(kwargs.get("modules"), path_id, 0)
new_modules, error = _parse_modules(
kwargs.get("modules"),
path_id,
0,
fallback_module_name=str(kwargs.get("path_name") or "").strip()[:200],
)
if error:
return ToolResult(content=error, success=False)
@@ -1069,38 +1127,115 @@ class MasteryLeaveTool(BaseTool):
)
# Ordered by how well each key names the thing for a learner: a real name
# first, a description only when there is nothing better, the raw id last.
_KP_NAME_KEYS = ("name", "title", "label", "objective", "topic", "description", "id")
_MODULE_NAME_KEYS = ("name", "title", "label", "module", "id")
_KP_LIST_KEYS = ("knowledge_points", "objectives", "points", "items")
def _humanized(value: str) -> str:
"""Turn an identifier-shaped name into a readable one.
Models that answer with ``{"id": "concept_framework"}`` mean the words,
not the key. Only reshape when the value really looks like an ASCII
identifier — CJK names carry no separators and must survive untouched.
"""
if " " in value or not value.isascii():
return value
if "_" not in value and "-" not in value:
return value
return re.sub(r"[_-]+", " ", value).strip().title()
def _display_name(raw: Any, keys: tuple[str, ...]) -> str:
"""First readable name *raw* offers under *keys*, or ``""``."""
if isinstance(raw, str):
return _humanized(raw.strip())[:200]
if not isinstance(raw, dict):
return ""
for key in keys:
value = raw.get(key)
if isinstance(value, str) and value.strip():
return _humanized(value.strip())[:200]
return ""
def _raw_knowledge_points(raw: dict[str, Any]) -> list[Any] | None:
"""The knowledge-point list *raw* declares, or ``None`` if it declares none."""
for key in _KP_LIST_KEYS:
value = raw.get(key)
if isinstance(value, list):
return value
return None
def _normalized_module_tree(
raw_modules: Any, fallback_module_name: str
) -> list[tuple[str, list[Any]]]:
"""Reduce whatever the model emitted to ``[(module name, knowledge points)]``.
The tool schema asks for ``[{name, knowledge_points: [{name, type}]}]``, but
DeepTutor runs on whatever model the learner brings, and smaller ones
routinely answer with ``objectives`` instead of ``modules``, ``title``
instead of ``name``, bare strings instead of knowledge-point objects, or a
flat objective list with no module layer at all (#1019). Every one of those
used to be dropped silently, leaving an empty path and no error the learner
could see. Read the meaning instead of rejecting the shape.
"""
if isinstance(raw_modules, dict):
for key in ("modules", *_KP_LIST_KEYS):
value = raw_modules.get(key)
if isinstance(value, list):
raw_modules = value
break
if not isinstance(raw_modules, list):
return []
entries: list[tuple[str, list[Any]]] = []
flat: list[Any] = []
for raw in raw_modules:
nested = _raw_knowledge_points(raw) if isinstance(raw, dict) else None
if nested:
entries.append((_display_name(raw, _MODULE_NAME_KEYS), nested))
elif nested is None:
# No knowledge-point list at all: the model flattened the tree and
# this entry is itself an objective.
flat.append(raw)
if flat:
entries.append((fallback_module_name, flat))
return entries
def _parse_modules(
raw_modules: Any, path_id: str, offset: int
raw_modules: Any, path_id: str, offset: int, fallback_module_name: str = ""
) -> tuple[list[LearningModule], str | None]:
"""Validate the model-designed module tree into engine models.
Ids are generated server-side (``<path>_m<i>_kp<j>``) so the model never
controls storage keys; unknown knowledge types fall back to 'concept'.
"""
if not isinstance(raw_modules, list) or not raw_modules:
return [], "mastery_build needs a non-empty 'modules' array."
entries = _normalized_module_tree(raw_modules, fallback_module_name or "Objectives")
if not entries:
return [], _BUILD_SHAPE_ERROR
modules: list[LearningModule] = []
for i, raw in enumerate(raw_modules):
if not isinstance(raw, dict):
continue
index = offset + i
name = str(raw.get("name") or "").strip()[:200]
if not name:
continue
for i, (raw_name, raw_kps) in enumerate(entries):
index = offset + len(modules)
module_id = f"{path_id}_m{index}"
name = raw_name or fallback_module_name or f"Module {index + 1}"
kps: list[KnowledgePoint] = []
for j, raw_kp in enumerate(raw.get("knowledge_points") or []):
if not isinstance(raw_kp, dict):
continue
kp_name = str(raw_kp.get("name") or "").strip()[:200]
for raw_kp in raw_kps:
kp_name = _display_name(raw_kp, _KP_NAME_KEYS)
if len(kp_name) < 2:
continue
kp_type = str(raw_kp.get("type") or "concept").strip().lower()
if kp_type not in _ALLOWED_KP_TYPES:
kp_type = "concept"
kp_type = "concept"
if isinstance(raw_kp, dict):
kp_type = str(raw_kp.get("type") or "concept").strip().lower()
if kp_type not in _ALLOWED_KP_TYPES:
kp_type = "concept"
kps.append(
KnowledgePoint(
id=f"{module_id}_kp{j}",
id=f"{module_id}_kp{len(kps)}",
name=kp_name,
type=KnowledgeType(kp_type),
module_id=module_id,
@@ -1110,7 +1245,7 @@ def _parse_modules(
continue
modules.append(LearningModule(id=module_id, name=name, order=index, knowledge_points=kps))
if not modules:
return [], "No valid modules: each module needs a name and at least one knowledge point."
return [], _BUILD_SHAPE_ERROR
return modules, None
@@ -1118,6 +1253,7 @@ MASTERY_TOOL_TYPES: tuple[type[BaseTool], ...] = (
MasteryStatusTool,
MasteryQuizTool,
MasteryGradeTool,
MasterySkipQuestionTool,
MasteryAssessTool,
MasteryBuildTool,
MasteryPathsTool,
@@ -1135,6 +1271,7 @@ __all__ = [
"MasteryLeaveTool",
"MasteryPathsTool",
"MasteryQuizTool",
"MasterySkipQuestionTool",
"MasteryStatusTool",
"MasterySwitchTool",
]
@@ -4,7 +4,7 @@ You are solving a problem end to end. Be rigorous: plan, work each step with the
FIRST, before doing anything else, call `solve_plan` with a short analysis and an ordered list of steps (2-6 for most problems; a single step is fine for a trivial one). Never start solving before you have called `solve_plan`.
Then work the plan one step at a time:
- Do the step's actual work with the available tools — `code_execution` for calculation / plotting / numeric checks, `rag` / `read_source` when materials are attached, `web_search` / `web_fetch` for facts you don't know, `reason` for a hard sub-derivation, `exec` to produce a file (a worked-solution PDF, a chart, a spreadsheet).
- Do the step's actual work with the available tools — `code_execution` for calculation / plotting / numeric checks and Python-generated files (a worked-solution PDF, a chart, a spreadsheet), `rag` / `read_source` when materials are attached, `web_search` / `web_fetch` for facts you don't know, `reason` for a hard sub-derivation, and `exec` only for genuinely shell-only commands.
- For a problem with a diagram, or a geometry problem where a figure helps, call `geogebra_analysis` to reconstruct the figure as a GeoGebra applet, then solve using it.
- After finishing a step, call `solve_finish_step` with its id and a short summary of what it established. This records the result and frees up context. Do not skip steps; do not mark a step done before its work is actually complete.
@@ -4,7 +4,7 @@
**第一件事**:在做任何事之前,先调用 `solve_plan`,给出简短分析和一个有序的步骤列表(多数题目 2-6 步;很简单的题一步也行)。在调用 `solve_plan` 之前,绝不开始求解。
然后按计划逐步推进,一次一步:
- 用合适的工具真正完成这一步的工作——`code_execution` 做计算/作图/数值验算,`rag` / `read_source` 在挂了材料时检索,`web_search` / `web_fetch` 查你不确定的事实,`reason` 做一段困难的子推导,`exec` 生成文件(解题 PDF、图表、表格)。
- 用合适的工具真正完成这一步的工作——`code_execution` 做计算/作图/数值验算以及用 Python 生成文件(解题 PDF、图表、表格),`rag` / `read_source` 在挂了材料时检索,`web_search` / `web_fetch` 查你不确定的事实,`reason` 做一段困难的子推导,`exec` 只用于真正必须使用 shell 的命令。
- 带配图的题、或画个图有助于理解的几何题,调用 `geogebra_analysis` 把图形还原成 GeoGebra 图形,再据此求解。
- 完成一步后,调用 `solve_finish_step`,传入步骤 id 和这一步结论的简短总结。这会记录结果并释放上下文。不要跳步;不要在工作真正完成前就把步骤标记为完成。
+13 -2
View File
@@ -8,9 +8,17 @@ from typing import Any
def assistant_message_with_tool_calls(
content: str,
tool_calls: list[dict[str, Any]],
*,
reasoning_content: str | None = None,
) -> dict[str, Any]:
"""Build the assistant message that precedes tool result messages."""
return {
"""Build the assistant message that precedes tool result messages.
``reasoning_content`` is optional: DeepSeek thinking-mode Chat Completions
requires the prior round's reasoning to be echoed on the assistant turn
that issued the tool calls (#1058). Responses-API replay is handled
separately via ``_responses_output_items``.
"""
message: dict[str, Any] = {
"role": "assistant",
"content": content or None,
"tool_calls": [
@@ -25,6 +33,9 @@ def assistant_message_with_tool_calls(
for tool_call in tool_calls
],
}
if reasoning_content:
message["reasoning_content"] = reasoning_content
return message
__all__ = ["assistant_message_with_tool_calls"]
+11 -2
View File
@@ -14,6 +14,8 @@ from dataclasses import dataclass
import re
from typing import TYPE_CHECKING, Any
from deeptutor.utils.text_display import decode_escaped_unicode_for_display
if TYPE_CHECKING:
from deeptutor.learning.models import PendingQuestion
@@ -270,9 +272,16 @@ def public_pending_question(pending: PendingQuestion) -> PublicPendingQuestion:
)
return PublicPendingQuestion(
question_id=pending.question_id,
prompt=pending.prompt,
prompt=decode_escaped_unicode_for_display(pending.prompt),
question_type=pending.question_type,
options=options,
options=tuple(
PublicPendingOption(
id=option.id,
label=decode_escaped_unicode_for_display(option.label),
body=decode_escaped_unicode_for_display(option.body),
)
for option in options
),
)
@@ -0,0 +1,156 @@
"""``mastery_build`` must read the module tree real models actually emit.
The tool schema asks for ``[{name, knowledge_points: [{name, type}]}]``, but
DeepTutor runs on whatever model the learner brings. The variants below were
observed in the wild (#1019) on gemma4, qwen3.5 and gpt-oss; every one of them
used to be dropped silently, leaving an empty path in Learning Space with no
error the learner could see.
"""
from __future__ import annotations
from deeptutor.capabilities.mastery.tools import _parse_modules
def _names(modules) -> list[tuple[str, list[str]]]:
return [(m.name, [kp.name for kp in m.knowledge_points]) for m in modules]
def test_canonical_shape_is_unchanged() -> None:
modules, error = _parse_modules(
[{"name": "Basics", "knowledge_points": [{"name": "Number bases", "type": "memory"}]}],
"p1",
0,
)
assert error is None
assert _names(modules) == [("Basics", ["Number bases"])]
assert modules[0].knowledge_points[0].type.value == "memory"
def test_objectives_key_with_title_instead_of_name() -> None:
"""Variant 1: wrong top-level key, ``title`` rather than ``name``."""
modules, error = _parse_modules(
{
"objectives": [
{
"title": "Layer basics",
"objectives": [{"id": "l1", "title": "Layer order", "type": "concept"}],
}
]
},
"p1",
0,
)
assert error is None
assert _names(modules) == [("Layer basics", ["Layer order"])]
def test_knowledge_points_as_bare_strings() -> None:
"""Variant 2: knowledge points arrive as plain strings."""
modules, error = _parse_modules(
[{"name": "Frames", "knowledge_points": ["concept_framework", "Data model"]}],
"p1",
0,
)
assert error is None
assert _names(modules) == [("Frames", ["Concept Framework", "Data model"])]
def test_knowledge_points_carrying_only_an_id() -> None:
"""Variant 3: knowledge-point dicts with nothing but an id."""
modules, error = _parse_modules(
[{"name": "Selection", "knowledge_points": [{"id": "quick-mask"}]}],
"p1",
0,
)
assert error is None
assert _names(modules) == [("Selection", ["Quick Mask"])]
def test_flat_objective_list_without_a_module_layer() -> None:
"""Variant 4: no module layer at all — one implicit module holds them."""
modules, error = _parse_modules(
[
{"id": "kp1", "title": "Bit shifting", "type": "procedure"},
{"id": "kp2", "title": "Two's complement", "type": "concept"},
],
"p1",
0,
fallback_module_name="Computer architecture",
)
assert error is None
assert _names(modules) == [("Computer architecture", ["Bit shifting", "Two's complement"])]
def test_cjk_names_are_never_reshaped() -> None:
"""Humanising is for ASCII identifiers only; CJK names pass through."""
modules, error = _parse_modules(
[{"name": "数制转换", "knowledge_points": [{"name": "二进制转十六进制"}]}],
"p1",
0,
)
assert error is None
assert _names(modules) == [("数制转换", ["二进制转十六进制"])]
def test_ids_are_still_server_generated_and_sequential() -> None:
modules, _ = _parse_modules(
[
{"name": "A", "knowledge_points": ["one", "two"]},
{"name": "B", "knowledge_points": ["three"]},
],
"path",
0,
)
assert [m.id for m in modules] == ["path_m0", "path_m1"]
assert [kp.id for kp in modules[0].knowledge_points] == ["path_m0_kp0", "path_m0_kp1"]
assert [kp.id for kp in modules[1].knowledge_points] == ["path_m1_kp0"]
def test_unreadable_input_explains_the_expected_shape() -> None:
"""The failure must name the schema, not just say 'no valid modules'."""
modules, error = _parse_modules([], "p1", 0)
assert modules == []
assert error is not None
assert "knowledge_points" in error and "memory|procedure|concept|design" in error
def test_modules_without_any_readable_objective_are_rejected() -> None:
modules, error = _parse_modules(
[{"name": "Empty", "knowledge_points": [{"type": "memory"}]}], "p1", 0
)
assert modules == []
assert error is not None
def test_flat_objectives_named_only_by_description() -> None:
"""Variant 4 exactly as reported: description + id + type, no name key."""
modules, error = _parse_modules(
[
{"id": "kp1", "description": "Convert between number bases", "type": "procedure"},
{"id": "kp2", "description": "Read a truth table", "type": "concept"},
],
"p1",
0,
fallback_module_name="Digital logic",
)
assert error is None
assert _names(modules) == [
("Digital logic", ["Convert between number bases", "Read a truth table"])
]
def test_a_real_name_always_beats_a_description_or_id() -> None:
modules, _ = _parse_modules(
[
{
"name": "Bases",
"knowledge_points": [
{"name": "Hex", "description": "a much longer explanation", "id": "kp_9"}
],
}
],
"p1",
0,
)
assert _names(modules) == [("Bases", ["Hex"])]
@@ -255,3 +255,22 @@ async def test_recover_options_from_turn_handles_missing_capability_and_errors()
assert await recover_options_from_turn(_Raising(), "turn_1", "q") == {}
assert await recover_options_from_turn(_FakeStore([]), "", "q") == {}
def test_public_pending_question_decodes_unicode_escapes() -> None:
from deeptutor.learning.models import PendingQuestion
from deeptutor.learning.pending import public_pending_question
escaped = "\\u300c\\u6570\\u5236\\u8f6c\\u6362\\u300d"
pending = PendingQuestion(
question_id="q1",
knowledge_point_id="kp1",
module_id="m1",
prompt=escaped,
question_type="choice",
expected_answer="A",
options=["A: first", "B: second"],
)
public = public_pending_question(pending)
assert public.prompt == "「数制转换」"
assert public.to_ask_user_dict()["prompt"] == "「数制转换」"
@@ -19,6 +19,7 @@ from deeptutor.tools.mastery_tool import (
MasteryLeaveTool,
MasteryPathsTool,
MasteryQuizTool,
MasterySkipQuestionTool,
MasteryStatusTool,
MasterySwitchTool,
)
@@ -223,6 +224,80 @@ async def test_grade_without_pending_fails(path_id):
assert result.success is False
@pytest.mark.asyncio
async def test_skip_question_unblocks_registration_without_credit(path_id):
await _build_basic(path_id)
status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
kp_id = status["next"]["knowledge_point_id"]
first = json.loads(
(
await MasteryQuizTool().execute(
_mastery_path_id=path_id,
knowledge_point_id=kp_id,
question="First?",
expected_answer="right",
)
).content
)
from deeptutor.learning.service import LearningService
LearningService().record_question_answer(
path_id,
"wrong",
interaction_id=first["question_id"],
)
before = LearningStore().load(path_id)
assert before is not None
mastery_before = before.mastery_levels.get(kp_id, 0.0)
result = await MasterySkipQuestionTool().execute(_mastery_path_id=path_id)
skipped = json.loads(result.content)
progress = LearningStore().load(path_id)
abandoned = LearningStore().get_interaction(path_id, first["question_id"])
assert result.success is True
assert skipped["skipped"] is True
assert skipped["question_id"] == first["question_id"]
assert skipped["next"]["action"] != "answer_pending"
assert progress is not None
assert progress.pending_question is None
assert progress.quiz_attempts == []
assert progress.mastery_levels.get(kp_id, 0.0) == mastery_before
assert abandoned is not None
assert abandoned.status == InteractionStatus.ABANDONED
assert LearningStore().get_active_interaction(path_id) is None
replacement = json.loads(
(
await MasteryQuizTool().execute(
_mastery_path_id=path_id,
knowledge_point_id=kp_id,
question="Replacement?",
expected_answer="right",
)
).content
)
assert replacement["status"] == "registered"
assert replacement["question_id"] != first["question_id"]
@pytest.mark.asyncio
async def test_skip_question_without_open_question_is_no_op(path_id):
await _build_basic(path_id)
before = LearningStore().load(path_id)
assert before is not None
result = await MasterySkipQuestionTool().execute(_mastery_path_id=path_id)
payload = json.loads(result.content)
after = LearningStore().load(path_id)
assert result.success is True
assert payload["skipped"] is False
assert payload["question_id"] == ""
assert after is not None
assert after.version == before.version
@pytest.mark.asyncio
async def test_quiz_unknown_kp_fails(path_id):
await _build_basic(path_id)
+12 -3
View File
@@ -143,6 +143,15 @@ def _scan_psutil(psutil: Any) -> tuple[list[ProcessMemory], bool]:
candidates = [root, *root.children(recursive=True)]
except psutil.Error:
return [], True
except (PermissionError, OSError):
# HarmonyOS / restricted /proc: ``children()`` walks every
# ``/proc/<pid>/stat`` via ``_ppid_map()``. Reading init's entry raises
# a raw ``PermissionError``, which is *not* a subclass of
# ``psutil.Error``, so it used to escape to the HTTP layer (#1076).
# The psutil-free walker already skips unreadable pids.
if sys.platform.startswith("linux"):
return _scan_proc()
return _scan_psutil_self(psutil)
found: list[ProcessMemory] = []
for proc in candidates:
@@ -152,7 +161,7 @@ def _scan_psutil(psutil: Any) -> tuple[list[ProcessMemory], bool]:
name = proc.name() or ""
try:
cmdline = " ".join(proc.cmdline()[:3])
except (psutil.AccessDenied, psutil.Error):
except (psutil.AccessDenied, psutil.Error, PermissionError, OSError):
cmdline = ""
found.append(
ProcessMemory(
@@ -161,7 +170,7 @@ def _scan_psutil(psutil: Any) -> tuple[list[ProcessMemory], bool]:
rss_bytes=rss,
)
)
except psutil.Error:
except (psutil.Error, PermissionError, OSError):
# The tree is live; a child exiting mid-walk is expected, not an error.
continue
if not any(p.pid == os.getpid() for p in found):
@@ -177,7 +186,7 @@ def _scan_psutil_self(psutil: Any) -> tuple[list[ProcessMemory], bool]:
return [
ProcessMemory(pid=proc.pid, label="backend", rss_bytes=int(proc.memory_info().rss))
], True
except psutil.Error:
except (psutil.Error, PermissionError, OSError):
return [], True
@@ -289,13 +289,11 @@ DEFAULT_GRAPHRAG_SETTINGS: dict[str, Any] = {
"dynamic_community_selection": False,
}
# LightRAG retrieval + indexing knobs (HKUDS/LightRAG via RAG-Anything). ``top_k``
# LightRAG retrieval + indexing knobs (HKUDS/LightRAG native SDK). ``top_k``
# is the number of entities/relations the query pulls; ``response_type`` mirrors
# GraphRAG's. These ride into ``QueryParam`` via the engine's aquery() call;
# wiring is defensive (an older RAG-Anything that rejects a kwarg degrades to a
# mode-only query). ``max_concurrent_files`` maps to RAGAnythingConfig's batch
# knob; ``llm_model_max_async`` / ``entity_extract_max_gleaning`` ride into
# LightRAG's own constructor via RAGAnything's ``lightrag_kwargs`` passthrough.
# GraphRAG's. These ride into ``QueryParam`` and the pinned SDK constructor.
# ``max_concurrent_files`` sizes the native parser worker pool after DeepTutor
# has frozen each ParseService result; pre-parsing itself remains serial.
DEFAULT_LIGHTRAG_SETTINGS: dict[str, Any] = {
"version": 1,
"top_k": 60,
@@ -14,6 +14,11 @@ logger = logging.getLogger(__name__)
class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
# Jina ignores `input_type` unless explicitly opted in. Enabling it changes
# vectors for both documents and queries, so the embedding signature must
# distinguish pre-role Jina indexes.
SUPPORTS_INPUT_TYPE = True
MODELS_INFO = {
"jina-embeddings-v3": {
"default": 1024,
+18 -3
View File
@@ -38,8 +38,13 @@ _MINIMAL_NOT_OFF_PATTERNS: dict[str, tuple[str, ...]] = {
}
_CUSTOM_MODEL_THINKING_STYLES: tuple[tuple[tuple[str, ...], str], ...] = (
(("qwen3", "qwen-3", "qwq", "qwen-plus"), "enable_thinking"),
(("deepseek-v4-pro", "deepseek-reasoner"), "thinking_type"),
(("deepseek-v4-pro", "deepseek-reasoner", "deepseek-r1"), "thinking_type"),
)
# Model substrings that default to thinking off — independent of binding name,
# so ``LLM_BINDING=openai`` pointed at DeepSeek with deepseek-v4-flash still
# sends ``thinking: disabled`` and avoids the mid-conversation
# ``reasoning_content must be passed back`` 400 (#1058).
_THINKING_DISABLED_BY_DEFAULT_MODELS: tuple[str, ...] = ("deepseek-v4-flash",)
_THINKING_DISABLED_BY_DEFAULT: tuple[tuple[str, str], ...] = (("deepseek", "deepseek-v4-flash"),)
@@ -56,11 +61,17 @@ def _custom_thinking_style(model_name: str) -> tuple[str, tuple[str, ...]]:
for patterns, style in _CUSTOM_MODEL_THINKING_STYLES:
if _matches(model_name, patterns):
return style, patterns
# Flash needs thinking_type so we can send ``disabled`` by default, but it
# must NOT inherit the high-effort patterns used by pro/reasoner.
if any(pattern in model_name.lower() for pattern in _THINKING_DISABLED_BY_DEFAULT_MODELS):
return "thinking_type", ()
return "", ()
def _disable_thinking_by_default(provider_name: str, model_name: str) -> bool:
normalized = model_name.strip().lower()
if any(pattern in normalized for pattern in _THINKING_DISABLED_BY_DEFAULT_MODELS):
return True
return any(
provider_name == provider and pattern in normalized
for provider, pattern in _THINKING_DISABLED_BY_DEFAULT
@@ -110,11 +121,15 @@ def build_openai_compatible_reasoning_kwargs(
thinking_style = _PROVIDER_THINKING_STYLES.get(provider_name, "")
if not patterns:
patterns = _PROVIDER_REASONING_PATTERNS.get(provider_name, ())
if provider_name == "custom":
# Infer style from the model id when the binding has none of its own —
# covers ``custom`` endpoints and ``openai`` bindings aimed at DeepSeek /
# Qwen gateways (#1058).
if not thinking_style:
custom_style, custom_patterns = _custom_thinking_style(model_name)
if custom_style:
thinking_style = custom_style
patterns = custom_patterns
if not patterns:
patterns = custom_patterns
resolved_effort = reasoning_effort
if resolved_effort is None:
+1 -1
View File
@@ -127,7 +127,7 @@ def _absolutize_img_paths(blocks: list[dict], content_dir: Path) -> list[dict]:
"""Anchor relative ``img_path`` entries at ``content_dir``.
Engines (MinerU especially) emit ``img_path`` values like ``images/x.png``
relative to the content-list file. Consumers such as RAG-Anything resolve
relative to the content-list file. Consumers such as LightRAG resolve
them against their own working directory instead, so the images are never
found (issue #624). The cached JSON stays relative — paths are rewritten
only on load, keeping the cache dir relocatable.
+1 -1
View File
@@ -330,7 +330,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
default_api_base="https://api.deepseek.com",
thinking_style="thinking_type",
reasoning_model_patterns=("deepseek-v4-pro", "deepseek-reasoner"),
native_web_search_models=("deepseek-v4-flash",),
native_web_search_models=("deepseek-v4-flash", "deepseek-v4-pro"),
),
ProviderSpec(
name="gemini",
@@ -12,14 +12,21 @@ logger = logging.getLogger(__name__)
def signature_from_config(config: Any) -> EmbeddingSignature:
"""Build a stable RAG index signature from an embedding config object."""
binding = (getattr(config, "binding", "") or "").strip().lower()
# Role support is a vector-space change. Jina previously sent no task, so
# its role-aware indexes need a different signature. Providers that were
# already role-aware before signatures gained this field keep the blank
# value to avoid invalidating compatible indexes.
role_semantics = "jina-task" if binding == "jina" else ""
return EmbeddingSignature(
binding=(getattr(config, "binding", "") or "").strip().lower(),
binding=binding,
model=(getattr(config, "model", "") or "").strip(),
dimension=int(getattr(config, "dim", 0) or 0),
base_url=(
getattr(config, "effective_url", None) or getattr(config, "base_url", None) or ""
).strip(),
api_version=(getattr(config, "api_version", "") or "").strip(),
role_semantics=role_semantics,
)
+1 -1
View File
@@ -9,7 +9,7 @@ today:
* ``graphrag`` — local knowledge-graph retrieval (microsoft/graphrag);
optional dependency, ``pip install 'deeptutor[graphrag]'``.
* ``lightrag`` — graph + vector retrieval (HKUDS/LightRAG, multimodal
via RAG-Anything); optional dependency,
via the LightRAG native pipeline); optional dependency,
``pip install 'deeptutor[rag-lightrag]'``.
* ``lightrag-server`` — retrieval offloaded to an external, standalone
LightRAG server the user runs. No local index: each
+47 -3
View File
@@ -52,10 +52,15 @@ class EmbeddingSignature:
dimension: int
base_url: str
api_version: str
role_semantics: str = ""
def hash(self) -> str:
"""Short hex digest used as the stable signature."""
canonical = json.dumps(asdict(self), sort_keys=True, ensure_ascii=False)
fields = asdict(self)
role_semantics = fields.pop("role_semantics")
if role_semantics:
fields["role_semantics"] = role_semantics
canonical = json.dumps(fields, sort_keys=True, ensure_ascii=False)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
@@ -113,11 +118,50 @@ def _next_flat_version_dir(kb_dir: Path) -> Path:
return kb_dir / f"{VERSION_PREFIX}{(max(existing) if existing else 0) + 1}"
def _native_lightrag_output_ready(version_dir: Path, meta: dict[str, Any]) -> bool:
workspace = str(meta.get("workspace") or "").strip()
if workspace:
workspace_path = Path(workspace)
if workspace_path.is_absolute() or workspace_path.name != workspace:
return False
status_path = version_dir / workspace / "kv_store_doc_status.json"
else:
# Transitional/test layouts may still keep the status store flat.
status_path = version_dir / "kv_store_doc_status.json"
payload = _read_json(status_path)
if not payload:
return False
return any(
isinstance(row, dict)
and (str(row.get("status") or "").lower() == "processed" or bool(row.get("chunks_list")))
for row in payload.values()
)
def _entry_from_flat_version(version_dir: Path) -> dict[str, Any]:
meta = _read_json(version_dir / META_FILENAME) or {}
stored_meta = _read_json(version_dir / META_FILENAME)
meta = dict(stored_meta or {})
meta.setdefault("version", version_dir.name)
meta.setdefault("signature", meta.get("signature") or version_dir.name)
meta["ready"] = _is_storage_ready(version_dir)
has_provider_output = _is_storage_ready(version_dir)
# Legacy flat stores from other providers predate metadata, so their
# established readiness rule remains output-based. A native LightRAG
# candidate is identifiable before publication by its doc-status/ingress
# files and must fail closed until schema-2 metadata is atomically written.
is_unpublished_lightrag_candidate = stored_meta is None and (
(version_dir / "kv_store_doc_status.json").exists()
or (version_dir / "deeptutor_ingress").exists()
)
ready = has_provider_output and not is_unpublished_lightrag_candidate
if stored_meta is not None and stored_meta.get("provider") == "lightrag":
adapter_schema = stored_meta.get("lightrag_adapter_schema")
if adapter_schema is not None:
ready = bool(
adapter_schema == 2
and stored_meta.get("state") == "published"
and _native_lightrag_output_ready(version_dir, stored_meta)
)
meta["ready"] = ready
meta["storage_path"] = str(version_dir)
meta["version_path"] = str(version_dir)
meta["layout"] = "flat"
@@ -1,15 +1,15 @@
"""LightRAG / RAG-Anything knowledge-base engine.
"""Native LightRAG knowledge-base engine.
A graph-based RAG provider built on HKUDS/LightRAG (multimodal via
HKUDS/RAG-Anything). It consumes DeepTutor's shared parse layer for document
parsing and exposes LightRAG's native query modes (naive/local/global/hybrid/mix)
through the per-KB ``search_mode``.
A graph-based RAG provider built directly on HKUDS/LightRAG. It consumes
DeepTutor's shared parse layer for document parsing and exposes LightRAG's
native query modes (naive/local/global/hybrid/mix) through the per-KB
``search_mode``.
Modules:
* ``block_policy`` — versioned MinerU block classification before indexing.
* ``config`` — availability + mode helpers + the LLM/vision/embedding adapters.
* ``storage`` — per-KB version-dir layout + readiness marker.
* ``engine`` — the ONLY module importing ``raganything``/``lightrag``.
* ``engine`` — constructs the exact supported LightRAG SDK version.
* ``pipeline`` — :class:`LightRagPipeline` implementing the ``RAGPipeline`` contract.
"""
@@ -1,9 +1,9 @@
"""Versioned MinerU block policy for LightRAG indexing.
MinerU's legacy ``content_list.json`` mixes semantic document content with
page-layout helpers. DeepTutor retains the raw parser cache for audit and
derives an independent, deep-copied list for indexing so RAG-Anything never
needs to decide which parser blocks are semantic.
page-layout helpers. DeepTutor retains the raw parser cache for audit and
derives an independent, deep-copied list before the native LightRAG Sidecar
bridge decides which parser blocks are semantic.
"""
from __future__ import annotations
@@ -1,16 +1,9 @@
"""Bridge DeepTutor's runtime config into LightRAG / RAG-Anything.
LightRAG (HKUDS/LightRAG) is a text knowledge-graph RAG engine; its multimodal
story is RAG-Anything (HKUDS/RAG-Anything), built on top of LightRAG. The
``lightrag`` provider uses RAG-Anything so multimodal content (the parse layer's
``content_list``) becomes graph entities, while text-only documents fall back to
a plain text insert.
"""Bridge DeepTutor runtime configuration into the LightRAG 1.5 native SDK.
This module is the decoupling seam: it exposes availability + mode helpers and
builds the three adapters LightRAG needs from DeepTutor's already-resolved LLM /
embedding clients. It imports neither RAG-Anything nor LightRAG at module load —
the adapter builders import ``lightrag.utils`` lazily (only the embedding wrapper
needs it), and engine construction lives in ``engine.py``.
builds the three adapters LightRAG needs from DeepTutor's already-resolved LLM,
vision, and embedding clients. LightRAG imports remain lazy so every other RAG
provider can import without the optional extra installed.
Decoupling notes:
* ``llm_model_func`` / ``vision_model_func`` wrap DeepTutor's unified model
@@ -45,7 +38,7 @@ DEFAULT_MODE = "hybrid"
# Conservative cap for the embedding wrapper when the model doesn't advertise one.
_DEFAULT_MAX_TOKEN_SIZE = 8192
# Keep retries at the LightRAG adapter boundary so RAG-Anything receives one
# Keep retries at the LightRAG adapter boundary so the SDK receives one
# predictable policy for both text and vision calls. Provider retries are disabled
# on every attempt to prevent the two retry layers from multiplying.
_ADAPTER_MAX_ATTEMPTS = 3
@@ -59,7 +52,7 @@ _HTTP_STATUS_PATTERN = re.compile(
class LightRagNotAvailableError(RuntimeError):
"""Raised when the optional ``raganything`` dependency is not installed."""
"""Raised when the optional ``lightrag-hku`` dependency is not installed."""
class LightRagNotConfiguredError(RuntimeError):
@@ -138,12 +131,12 @@ async def _run_adapter_with_retry(
def is_lightrag_available() -> bool:
"""True when RAG-Anything (which bundles LightRAG) can be imported.
"""True when the native LightRAG SDK can be imported.
Opt-in extra: ``pip install 'deeptutor[rag-lightrag]'``. Until installed the
provider is hidden / blocked in the UI.
"""
return importlib.util.find_spec("raganything") is not None
return importlib.util.find_spec("lightrag") is not None
def normalize_mode(mode: str | None) -> str:
@@ -157,12 +150,7 @@ def normalize_mode(mode: str | None) -> str:
def query_kwargs_from_settings() -> dict:
"""Extra ``aquery`` kwargs (top_k, response_type) from runtime settings.
Returned as a dict so the engine can pass them through to LightRAG's
``QueryParam`` and gracefully drop them if an older RAG-Anything rejects a
kwarg. Empty on any read error.
"""
"""``QueryParam`` values from runtime settings."""
try:
from deeptutor.services.config import load_lightrag_settings
@@ -176,34 +164,18 @@ def query_kwargs_from_settings() -> dict:
def indexing_kwargs_from_settings() -> dict:
"""``RAGAnythingConfig`` batch-processing knobs from runtime settings.
Only ``max_concurrent_files`` is exposed for now (issue #640); the config
object accepts several other batch/context knobs we deliberately leave on
RAG-Anything's own defaults. Empty on any read error, so a bad settings
file falls back to RAG-Anything's built-in default of 1.
"""
"""Native parser-pool knobs from runtime settings."""
try:
from deeptutor.services.config import load_lightrag_settings
settings = load_lightrag_settings()
return {"max_concurrent_files": int(settings.get("max_concurrent_files", 1))}
return {"max_parallel_parse_native": int(settings.get("max_concurrent_files", 1))}
except Exception:
return {}
def lightrag_kwargs_from_settings() -> dict:
"""Extra kwargs forwarded to LightRAG's own constructor via RAG-Anything's
``lightrag_kwargs`` passthrough.
``llm_model_max_async`` bounds how many concurrent LLM calls LightRAG's
internal priority queue issues (covers both query and entity-extraction
traffic, since both ride the same wrapped ``llm_model_func``).
``entity_extract_max_gleaning`` controls how many extra extraction passes
LightRAG runs per chunk to recover entities/relations the first pass
missed. Empty on any read error, so a bad settings file falls back to
LightRAG's own built-in defaults.
"""
def constructor_kwargs_from_settings() -> dict:
"""Direct LightRAG constructor knobs from runtime settings."""
try:
from deeptutor.services.config import load_lightrag_settings
@@ -248,7 +220,7 @@ def build_llm_model_func(*, io_bridge: OwnerLoopBridge | None = None):
def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):
"""Wrap DeepTutor's vision-capable callable for RAG-Anything's image step."""
"""Map rc2 ``image_inputs`` to DeepTutor's vision callable."""
from deeptutor.services.llm import get_llm_client
base = get_llm_client().get_vision_model_func()
@@ -257,10 +229,19 @@ def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):
prompt="",
system_prompt=None,
history_messages=None,
image_data=None,
image_inputs=None,
messages=None,
**_ignored,
):
if not isinstance(image_inputs, list) or len(image_inputs) != 1:
raise ValueError("LightRAG vision requests must contain exactly one image input")
payload = image_inputs[0]
if not isinstance(payload, dict):
raise ValueError("LightRAG vision image input must be an object")
image_data = payload.get("base64")
if not isinstance(image_data, str) or not image_data.strip():
raise ValueError("LightRAG vision image input requires a non-empty base64 value")
async def request():
return await base(
prompt or "",
@@ -269,12 +250,6 @@ def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):
image_data=image_data,
messages=messages,
max_retries=0,
# Never strip the image and answer anyway. The provider's
# stage-2 fallback exists to salvage a text answer from a model
# that turns out not to take images, but here the *whole point*
# of the call is the image: a description produced without it is
# invented, and it would be indexed as fact. Fail the image
# instead, and let the caller log and skip it.
allow_image_fallback=False,
)
@@ -283,6 +258,16 @@ def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):
return vision_model_func
def vision_model_available() -> bool:
"""Return whether the active DeepTutor model is explicitly vision-capable."""
try:
from deeptutor.services.llm import get_llm_client
return bool(get_llm_client().supports_multimodal_images())
except Exception:
return False
def build_embedding_func(*, io_bridge: OwnerLoopBridge | None = None):
"""Wrap DeepTutor's embedding client in LightRAG's ``EmbeddingFunc``."""
from lightrag.utils import EmbeddingFunc
@@ -334,8 +319,9 @@ __all__ = [
"normalize_mode",
"query_kwargs_from_settings",
"indexing_kwargs_from_settings",
"lightrag_kwargs_from_settings",
"constructor_kwargs_from_settings",
"build_llm_model_func",
"build_vision_model_func",
"vision_model_available",
"build_embedding_func",
]
@@ -1,23 +1,12 @@
"""Thin adapter over the RAG-Anything / LightRAG Python API.
This is the ONLY module that imports ``raganything`` / ``lightrag``. Everything
version-sensitive lives here, so an API shift between releases is a one-file
fix. All imports are lazy so DeepTutor runs fine without the optional dependency
installed.
A RAG-Anything instance is built from DeepTutor's LLM/vision/embedding adapters
(see ``config.py``) over a per-KB ``working_dir``. Documents are inserted as a
MinerU-style ``content_list`` (produced upstream by the parse layer), so the
multimodal step never re-parses anything; retrieval delegates to LightRAG's
native query modes.
"""
"""Exact-version adapter over the LightRAG 1.5 native Python SDK."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Iterable, Mapping
import hashlib
from importlib.metadata import PackageNotFoundError, version
import inspect
import logging
from pathlib import Path
from typing import Any
@@ -26,335 +15,441 @@ from .config import (
build_embedding_func,
build_llm_model_func,
build_vision_model_func,
constructor_kwargs_from_settings,
indexing_kwargs_from_settings,
lightrag_kwargs_from_settings,
normalize_mode,
query_kwargs_from_settings,
)
from .ingress import IngressError, StagedDocument, pending_root
from .worker import OwnerLoopBridge
logger = logging.getLogger(__name__)
LIGHTRAG_DISTRIBUTION = "lightrag-hku"
LIGHTRAG_VERSION = "1.5.7rc2"
PARSER_ENGINE = "deeptutor"
def _accepts(target: Any, name: str) -> bool:
"""Whether ``target``'s constructor takes a keyword called *name*.
class LightRagContractError(RuntimeError):
"""Raised when the pinned SDK returns a shape DeepTutor cannot trust."""
The settings knobs below ride on RAG-Anything parameters that arrived in
different releases — ``lightrag_kwargs`` only exists from ~1.2.5, while the
supported range starts at 1.0.1. Asking first keeps an older install
working on RAG-Anything's own defaults instead of dying with a TypeError
that takes the whole LightRAG engine down. Same defensive posture the query
path already takes for ``QueryParam`` kwargs.
"""
import inspect
def installed_version() -> str:
try:
return name in inspect.signature(target).parameters
except (TypeError, ValueError):
return False
return version(LIGHTRAG_DISTRIBUTION)
except PackageNotFoundError as exc:
raise LightRagContractError(
"LightRAG is not installed. Install `deeptutor[rag-lightrag]`."
) from exc
def _drop_unsupported(target: Any, kwargs: dict[str, Any], *, what: str) -> dict[str, Any]:
supported = {key: value for key, value in kwargs.items() if _accepts(target, key)}
for key in kwargs.keys() - supported.keys():
logger.warning(
"Installed RAG-Anything does not accept %s=%r on %s; leaving it at "
"the library default. Upgrade raganything to use this setting.",
key,
kwargs[key],
what,
def _require_exact_version() -> None:
current = installed_version()
if current != LIGHTRAG_VERSION:
raise LightRagContractError(
f"DeepTutor requires {LIGHTRAG_DISTRIBUTION}=={LIGHTRAG_VERSION}; found {current}"
)
return supported
def _build_config(config_cls: Any, working_dir: Path) -> Any:
knobs = _drop_unsupported(config_cls, indexing_kwargs_from_settings(), what="RAGAnythingConfig")
return config_cls(working_dir=str(working_dir), **knobs)
def _validate_component(value: str, *, label: str) -> str:
path = Path(str(value or ""))
if path.is_absolute() or ".." in path.parts or path.name != str(value):
raise IngressError(f"{label} must be a canonical basename: {value!r}")
if not path.name or path.name in {".", ".."}:
raise IngressError(f"{label} is empty or invalid")
return path.name
def _construct(rag_cls: Any, **kwargs: Any) -> Any:
extra = lightrag_kwargs_from_settings()
if extra and _accepts(rag_cls, "lightrag_kwargs"):
kwargs["lightrag_kwargs"] = extra
elif extra:
logger.warning(
"Installed RAG-Anything has no lightrag_kwargs passthrough; %s stay "
"at LightRAG's defaults. Upgrade raganything to use these settings.",
", ".join(sorted(extra)),
)
return rag_cls(**kwargs)
def _safe_candidate(root: Path, candidate: Path) -> Path | None:
if candidate.is_symlink() or not candidate.is_file():
return None
resolved_root = root.resolve(strict=True)
resolved = candidate.resolve(strict=True)
try:
resolved.relative_to(resolved_root)
except ValueError as exc:
raise IngressError(
f"LightRAG source resolver escaped version ingress: {candidate}"
) from exc
return resolved
def build_rag(working_dir: Path, *, io_bridge: OwnerLoopBridge | None = None) -> Any:
"""Construct a RAG-Anything instance rooted at ``working_dir``.
def _controlled_class():
from lightrag import LightRAG
Pinned to RAG-Anything's config-based constructor; this is the single spot
to touch if its API changes between releases.
"""
from raganything import RAGAnything, RAGAnythingConfig
class DeepTutorLightRAG(LightRAG):
def _resolve_source_file_for_parser(
self,
file_path: str,
*,
source_file: str | None = None,
parser_engine: str | None = None,
) -> str:
if parser_engine not in (None, PARSER_ENGINE):
raise IngressError(
f"Unsupported parser engine for DeepTutor ingress: {parser_engine}"
)
name = _validate_component(file_path, label="file_path")
if source_file is not None:
source_name = _validate_component(source_file, label="source_file")
if source_name != name:
raise IngressError(
f"LightRAG source hints disagree: {name!r} != {source_name!r}"
)
root = pending_root(Path(self.working_dir))
root.mkdir(parents=True, exist_ok=True)
matches = [
resolved
for candidate in (root / name, root / "__parsed__" / name)
if (resolved := _safe_candidate(root, candidate)) is not None
]
if len(matches) != 1:
reason = "missing" if not matches else "ambiguous"
raise IngressError(f"Version-local LightRAG source is {reason}: {name}")
return str(matches[0])
config = _build_config(RAGAnythingConfig, working_dir)
adapter_kwargs = {"io_bridge": io_bridge} if io_bridge is not None else {}
funcs = {
"llm_model_func": build_llm_model_func(**adapter_kwargs),
"vision_model_func": build_vision_model_func(**adapter_kwargs),
"embedding_func": build_embedding_func(**adapter_kwargs),
return DeepTutorLightRAG
_SUFFIXES = frozenset(
{
"txt",
"md",
"mdx",
"pdf",
"doc",
"docx",
"ppt",
"pptx",
"xls",
"xlsx",
"rtf",
"odt",
"tex",
"epub",
"html",
"htm",
"csv",
"json",
"xml",
"yaml",
"yml",
"log",
"conf",
"ini",
"properties",
"sql",
"sh",
"c",
"h",
"cpp",
"hpp",
"py",
"java",
"js",
"ts",
"swift",
"go",
"rb",
"php",
"css",
"scss",
"less",
"png",
"jpg",
"jpeg",
"webp",
"gif",
"bmp",
"tiff",
}
rag = _construct(RAGAnything, config=config, **funcs)
# DeepTutor always feeds RAG-Anything a pre-parsed ``content_list`` (the
# parse layer runs upstream via DeepTutor's own ParseService), so
# RAG-Anything's bundled document parser is never invoked. Its LightRAG init
# nevertheless runs a one-time installation check on its *default* parser
# (``mineru``); when MinerU isn't installed that check hard-fails indexing
# with "Parser 'mineru' is not properly installed" — even though the user
# picked an entirely different parse engine (see issue #594). Marking the
# check as already satisfied skips that spurious gate for a parser we don't
# use, while leaving the real pre-parsed insert path untouched.
rag._parser_installation_checked = True
return rag
)
async def insert(rag: Any, content_list: list[dict], *, file_name: str, doc_id: str) -> None:
"""Insert a pre-parsed ``content_list`` (multimodal-aware, no re-parsing)."""
await rag.insert_content_list(
content_list=content_list,
file_path=file_name,
doc_id=doc_id,
def _register_parser() -> None:
from lightrag.parser.registry import ParserSpec, register_parser
register_parser(
ParserSpec(
engine_name=PARSER_ENGINE,
impl="deeptutor.services.rag.pipelines.lightrag.parser:DeepTutorParser",
suffixes=_SUFFIXES,
queue_group="native",
)
)
def _managed_queue_funcs(lightrag: Any) -> Iterable[Callable[..., Any]]:
"""Yield each current LightRAG queue wrapper exactly once."""
role_funcs = getattr(lightrag, "role_llm_funcs", {})
candidates: list[object] = []
if isinstance(role_funcs, Mapping):
candidates.extend(role_funcs.values())
def workspace_for(working_dir: Path) -> str:
identity = str(Path(working_dir).resolve()).encode("utf-8")
return f"deeptutor_{hashlib.sha256(identity).hexdigest()[:16]}"
embedding = getattr(lightrag, "embedding_func", None)
def build_rag(
working_dir: Path,
*,
io_bridge: OwnerLoopBridge | None = None,
enable_vlm: bool = False,
) -> Any:
"""Construct one exact-version, version-isolated LightRAG instance."""
_require_exact_version()
_register_parser()
from lightrag.llm_roles import RoleLLMConfig
adapter_kwargs = {"io_bridge": io_bridge} if io_bridge is not None else {}
constructor = {
"working_dir": str(Path(working_dir)),
"workspace": workspace_for(working_dir),
"llm_model_func": build_llm_model_func(**adapter_kwargs),
"embedding_func": build_embedding_func(**adapter_kwargs),
"auto_manage_storages_states": False,
"vlm_process_enable": bool(enable_vlm),
**indexing_kwargs_from_settings(),
**constructor_kwargs_from_settings(),
}
if enable_vlm:
constructor["role_llm_configs"] = {
"vlm": RoleLLMConfig(func=build_vision_model_func(**adapter_kwargs))
}
return _controlled_class()(**constructor)
async def initialize(rag: Any) -> None:
result = rag.initialize_storages()
if inspect.isawaitable(result):
await result
async def enqueue(rag: Any, staged: list[StagedDocument]) -> str:
if not staged:
raise ValueError("Cannot enqueue an empty LightRAG batch")
return await rag.apipeline_enqueue_documents(
[""] * len(staged),
file_paths=[item.canonical_name for item in staged],
docs_format="pending_parse",
parse_engine=PARSER_ENGINE,
process_options=[item.process_options for item in staged],
chunk_options=[item.chunk_options for item in staged],
)
def _document_id(canonical_name: str) -> str:
from lightrag.utils import compute_mdhash_id
from lightrag.utils_pipeline import (
has_known_document_source,
normalize_document_file_path,
)
source = normalize_document_file_path(canonical_name)
if not has_known_document_source(source):
raise LightRagContractError(
f"LightRAG cannot derive a stable document ID for {canonical_name!r}"
)
return compute_mdhash_id(source, prefix="doc-")
async def confirmed_unaccepted(rag: Any, staged: list[StagedDocument]) -> list[StagedDocument]:
"""Return documents whose missing doc_status row was strictly confirmed."""
ids_by_name = {item.canonical_name: _document_id(item.canonical_name) for item in staged}
rows = await rag.doc_status.get_docs_by_ids(
list(ids_by_name.values()),
strict=True,
)
if not isinstance(rows, dict):
raise LightRagContractError("doc_status.get_docs_by_ids must return an object")
return [item for item in staged if ids_by_name[item.canonical_name] not in rows]
def _managed_queue_funcs(rag: Any) -> Iterable[Callable[..., Any]]:
role_funcs = getattr(rag, "role_llm_funcs", {})
candidates: list[object] = list(role_funcs.values()) if isinstance(role_funcs, Mapping) else []
embedding = getattr(rag, "embedding_func", None)
candidates.append(getattr(embedding, "func", None))
candidates.append(getattr(lightrag, "rerank_model_func", None))
candidates.append(getattr(rag, "rerank_model_func", None))
seen: set[int] = set()
for candidate in candidates:
if not callable(candidate) or id(candidate) in seen:
continue
seen.add(id(candidate))
yield candidate
if callable(candidate) and id(candidate) not in seen:
seen.add(id(candidate))
yield candidate
async def _shutdown_queues(lightrag: Any, *, cancel_pending: bool) -> None:
"""Bound cleanup of LightRAG's role, embedding, and rerank queues."""
async def _shutdown_queues(rag: Any, *, cancel_pending: bool) -> None:
shutdowns: list[Awaitable[Any]] = []
for func in _managed_queue_funcs(lightrag):
for func in _managed_queue_funcs(rag):
shutdown = getattr(func, "shutdown", None)
if callable(shutdown):
result = shutdown(graceful=not cancel_pending, timeout=5.0)
if inspect.isawaitable(result):
shutdowns.append(result)
if not shutdowns:
return
results = await asyncio.gather(*shutdowns, return_exceptions=True)
failures = [result for result in results if isinstance(result, BaseException)]
if failures:
raise RuntimeError(
f"Failed to shut down {len(failures)} LightRAG managed queue(s)"
) from failures[0]
if shutdowns:
results = await asyncio.gather(*shutdowns, return_exceptions=True)
failures = [item for item in results if isinstance(item, BaseException)]
if failures:
raise RuntimeError(
f"Failed to shut down {len(failures)} LightRAG queue(s)"
) from failures[0]
async def finalize(rag: Any, *, cancel_pending: bool) -> None:
"""Stop managed work before finalizing RAG-Anything storage resources."""
lightrag = getattr(rag, "lightrag", None)
if lightrag is not None:
await _shutdown_queues(lightrag, cancel_pending=cancel_pending)
finalizer = getattr(rag, "finalize_storages", None)
if not callable(finalizer):
return
result = finalizer()
await _shutdown_queues(rag, cancel_pending=cancel_pending)
result = rag.finalize_storages()
if inspect.isawaitable(result):
await result
async def ensure_ready(rag: Any) -> None:
"""Ensure RAG-Anything has an initialized LightRAG instance."""
if getattr(rag, "lightrag", None) is not None:
return
initializer = getattr(rag, "_ensure_lightrag_initialized", None)
if initializer is None:
return
result = await initializer()
if isinstance(result, dict) and result.get("success") is False:
raise RuntimeError(result.get("error") or "Failed to initialize LightRAG")
def _string(value: Any, *, label: str) -> str:
if not isinstance(value, str):
raise LightRagContractError(f"LightRAG query {label} must be a string")
return value
async def query(rag: Any, question: str, mode: str | None = None) -> str:
"""Run a LightRAG query and return the synthesized answer string.
def _records(data: dict[str, Any], key: str) -> list[dict[str, Any]]:
value = data.get(key)
if not isinstance(value, list) or not all(isinstance(item, dict) for item in value):
raise LightRagContractError(f"LightRAG query data.{key} must be an object array")
return value
Extra knobs (top_k, response_type) from the lightrag.json slice ride into
LightRAG's ``QueryParam`` via aquery's ``**kwargs``. Wiring is defensive: an
older RAG-Anything that rejects one of these kwargs falls back to a
mode-only query rather than failing the search.
"""
resolved = normalize_mode(mode) or DEFAULT_MODE
extra = query_kwargs_from_settings()
await ensure_ready(rag)
try:
result = await rag.aquery(question, mode=resolved, **extra)
except TypeError:
if extra:
logger.debug("RAG-Anything rejected extra query kwargs; retrying mode-only.")
result = await rag.aquery(question, mode=resolved)
def _query_sources(data: dict[str, Any], metadata: dict[str, Any]) -> list[dict[str, Any]]:
references = _records(data, "references")
ref_paths = {
str(item.get("reference_id")): str(item.get("file_path") or item.get("source") or "")
for item in references
if item.get("reference_id") is not None
}
sources: list[dict[str, Any]] = []
def add(kind: str, record: dict[str, Any], rank: int) -> None:
ref = str(record.get("reference_id") or "")
path = str(record.get("file_path") or ref_paths.get(ref, ""))
if kind == "chunk":
stable_id = str(record.get("chunk_id") or "")
title = Path(path).name if path else "LightRAG chunk"
content = _string(record.get("content", ""), label="chunk content")
elif kind == "entity":
stable_id = str(record.get("entity_name") or record.get("entity_id") or "")
title = stable_id or "LightRAG entity"
content = _string(record.get("description", ""), label="entity description")
else:
raise
return result if isinstance(result, str) else str(result)
src_id = str(record.get("src_id") or "")
tgt_id = str(record.get("tgt_id") or "")
stable_id = str(record.get("relation_id") or f"{src_id}->{tgt_id}")
title = stable_id or "LightRAG relationship"
content = _string(record.get("description", ""), label="relationship description")
item = {
"kind": kind,
"title": title,
"content": content,
"source": path,
"page": str(record.get("page") or ""),
"reference_id": ref,
"rank": rank,
}
if kind == "chunk":
item["chunk_id"] = stable_id
elif kind == "entity":
item.update(
{
"entity_id": stable_id,
"entity_name": str(record.get("entity_name") or ""),
"entity_type": str(record.get("entity_type") or ""),
"source_id": str(record.get("source_id") or ""),
}
)
else:
item.update(
{
"relation_id": stable_id,
"src_id": str(record.get("src_id") or ""),
"tgt_id": str(record.get("tgt_id") or ""),
"keywords": record.get("keywords"),
"weight": record.get("weight"),
"source_id": str(record.get("source_id") or ""),
}
)
sources.append(item)
for kind, key in (
("chunk", "chunks"),
("entity", "entities"),
("relationship", "relationships"),
):
for record in _records(data, key):
add(kind, record, len(sources) + 1)
for reference in references:
reference_id = str(reference.get("reference_id") or "")
path = str(reference.get("file_path") or reference.get("source") or "")
sources.append(
{
"kind": "reference",
"title": Path(path).name if path else reference_id or "LightRAG reference",
"content": "",
"source": path,
"page": str(reference.get("page") or ""),
"reference_id": reference_id,
"rank": len(sources) + 1,
"reference": reference,
}
)
sources.append(
{
"kind": "query_metadata",
"title": "LightRAG query metadata",
"content": "",
"source": "",
"page": "",
"reference_id": "",
"rank": len(sources) + 1,
"metadata": metadata,
}
)
return sources
async def query_with_sources(
rag: Any, question: str, mode: str | None = None
) -> tuple[str, list[dict[str, Any]]]:
"""Return a LightRAG answer together with its structured provenance.
from lightrag import QueryParam
``RAGAnything.aquery`` owns the answer path, including its optional VLM
enhancement. LightRAG exposes the records used for retrieval separately via
``aquery_data``. Keeping those calls separate preserves the existing answer
behavior while allowing DeepTutor to surface citation metadata.
"""
answer = await query(rag, question, mode)
return answer, await query_sources(rag, question, mode)
async def query_sources(rag: Any, question: str, mode: str | None = None) -> list[dict[str, Any]]:
"""Fetch and normalize the structured records used by a LightRAG query.
``aquery_data`` was added by LightRAG after some supported RAG-Anything
releases. Missing or failed provenance must not turn a successful answer
into a failed user request, so older installations gracefully return no
citations.
"""
await ensure_ready(rag)
lightrag = getattr(rag, "lightrag", None)
aquery_data = getattr(lightrag, "aquery_data", None)
if not callable(aquery_data):
logger.debug("Installed LightRAG has no structured query data API.")
return []
resolved = normalize_mode(mode) or DEFAULT_MODE
extra = query_kwargs_from_settings()
try:
from lightrag import QueryParam
try:
result = await aquery_data(question, param=QueryParam(mode=resolved, **extra))
except TypeError:
if not extra:
raise
logger.debug("LightRAG rejected extra provenance query kwargs; retrying mode-only.")
result = await aquery_data(question, param=QueryParam(mode=resolved))
except Exception as exc:
logger.warning("LightRAG provenance lookup failed; omitting citations: %s", exc)
return []
return _query_data_to_sources(result)
def _query_data_to_sources(result: Any) -> list[dict[str, Any]]:
"""Map LightRAG's structured retrieval result to DeepTutor citations."""
param = QueryParam(
mode=normalize_mode(mode) or DEFAULT_MODE,
stream=False,
include_references=True,
**query_kwargs_from_settings(),
)
result = await rag.aquery_llm(question, param=param)
if not isinstance(result, dict):
return []
raise LightRagContractError("LightRAG query response must be an object")
if result.get("status") != "success":
message = result.get("message")
raise LightRagContractError(
str(message).strip()
if isinstance(message, str) and message.strip()
else "LightRAG retrieval failed"
)
response = result.get("llm_response")
data = result.get("data")
if not isinstance(data, dict):
return []
reference_paths = {
str(record.get("reference_id")): str(record.get("file_path"))
for record in data.get("references", [])
if isinstance(record, dict) and record.get("reference_id") and record.get("file_path")
}
sources: list[dict[str, Any]] = []
def source_path(record: dict[str, Any]) -> str:
return str(
record.get("file_path") or reference_paths.get(str(record.get("reference_id")), "")
)
def source_title(path: str, fallback: str) -> str:
return Path(path).name if path else fallback
for record in data.get("chunks", []):
if not isinstance(record, dict):
continue
path = source_path(record)
content = str(record.get("content") or "")
chunk_id = str(record.get("chunk_id") or "")
if not (path or content or chunk_id):
continue
sources.append(
{
"title": source_title(path, "LightRAG chunk"),
"content": content[:200],
"source": path,
"page": str(record.get("page") or ""),
"chunk_id": chunk_id,
"reference_id": str(record.get("reference_id") or ""),
}
)
for record in data.get("entities", []):
if not isinstance(record, dict):
continue
path = source_path(record)
entity_id = str(record.get("entity_name") or record.get("entity_id") or "")
description = str(record.get("description") or "")
if not (path or entity_id or description):
continue
sources.append(
{
"title": entity_id or source_title(path, "LightRAG entity"),
"content": description[:200],
"source": path,
"page": str(record.get("page") or ""),
"entity_id": entity_id,
"entity_type": str(record.get("entity_type") or ""),
"source_id": str(record.get("source_id") or ""),
"reference_id": str(record.get("reference_id") or ""),
}
)
for record in data.get("relationships", []):
if not isinstance(record, dict):
continue
path = source_path(record)
source_id = str(record.get("src_id") or "")
target_id = str(record.get("tgt_id") or "")
relation_id = str(record.get("relation_id") or f"{source_id}->{target_id}")
description = str(record.get("description") or "")
if not (path or relation_id or description):
continue
sources.append(
{
"title": relation_id or source_title(path, "LightRAG relationship"),
"content": description[:200],
"source": path,
"page": str(record.get("page") or ""),
"relation_id": relation_id,
"source_entity_id": source_id,
"target_entity_id": target_id,
"source_id": str(record.get("source_id") or ""),
"reference_id": str(record.get("reference_id") or ""),
}
)
return sources
metadata = result.get("metadata")
if (
not isinstance(response, dict)
or not isinstance(data, dict)
or not isinstance(metadata, dict)
):
raise LightRagContractError("LightRAG query response is missing structured fields")
if response.get("is_streaming") is not False:
raise LightRagContractError("LightRAG returned streaming output for a non-streaming query")
content = _string(response.get("content"), label="llm_response.content")
return content, _query_sources(data, metadata)
__all__ = [
"LIGHTRAG_DISTRIBUTION",
"LIGHTRAG_VERSION",
"LightRagContractError",
"PARSER_ENGINE",
"build_rag",
"ensure_ready",
"confirmed_unaccepted",
"enqueue",
"finalize",
"insert",
"query",
"initialize",
"installed_version",
"query_with_sources",
"workspace_for",
]
@@ -0,0 +1,364 @@
"""Freeze DeepTutor parse results into version-local LightRAG ingress bundles."""
from __future__ import annotations
from copy import deepcopy
from dataclasses import dataclass
import hashlib
import json
import os
from pathlib import Path
import shutil
from typing import Any
import uuid
from deeptutor.services.file_io import atomic_write_json
from deeptutor.services.parsing.types import ParsedDocument
from . import block_policy
PARSER_BRIDGE_SCHEMA = 1
INGRESS_DIRNAME = "deeptutor_ingress"
PENDING_DIRNAME = "pending"
BUNDLES_DIRNAME = "bundles"
MANIFEST_FILENAME = "manifest.json"
class IngressError(RuntimeError):
"""Raised when an ingress bundle crosses or violates its trust boundary."""
@dataclass(frozen=True)
class StagedDocument:
canonical_name: str
source_path: Path
bundle_dir: Path
manifest_path: Path
process_options: str
chunk_options: dict[str, Any]
audit_ledger: dict[str, Any] | None
def ingress_root(working_dir: Path) -> Path:
return Path(working_dir) / INGRESS_DIRNAME
def pending_root(working_dir: Path) -> Path:
return ingress_root(working_dir) / PENDING_DIRNAME
def bundles_root(working_dir: Path) -> Path:
return ingress_root(working_dir) / BUNDLES_DIRNAME
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _contained_regular_file(root: Path, path: Path, *, label: str) -> Path:
if root.is_symlink() or not root.is_dir():
raise IngressError(f"Bundle root must be an ordinary directory: {root}")
try:
relative = path.relative_to(root)
except ValueError as exc:
raise IngressError(f"{label} escapes its bundle root: {path}") from exc
current = root
for part in relative.parts:
current = current / part
if current.is_symlink():
raise IngressError(f"{label} must not traverse a symbolic link: {current}")
if path.is_symlink():
raise IngressError(f"{label} must not be a symbolic link: {path}")
try:
resolved_root = root.resolve(strict=True)
resolved = path.resolve(strict=True)
resolved.relative_to(resolved_root)
except (FileNotFoundError, ValueError) as exc:
raise IngressError(f"{label} escapes its bundle root: {path}") from exc
stat = resolved.stat()
if not resolved.is_file() or stat.st_nlink != 1:
raise IngressError(f"{label} must be an ordinary, unlinked file: {path}")
return resolved
def _copy_regular(source: Path, target: Path, *, allowed_root: Path | None = None) -> str:
if source.is_symlink() or not source.is_file():
raise IngressError(f"Source is not an ordinary file: {source}")
resolved_source = source.resolve(strict=True)
if resolved_source.stat().st_nlink != 1:
raise IngressError(f"Source must not be hard-linked: {source}")
if allowed_root is not None:
try:
resolved_source.relative_to(allowed_root.resolve(strict=True))
except ValueError as exc:
raise IngressError(f"Source escapes allowed root: {source}") from exc
source_digest = _sha256(resolved_source)
target.parent.mkdir(parents=True, exist_ok=True)
with resolved_source.open("rb") as src, target.open("xb") as dst:
shutil.copyfileobj(src, dst, length=1024 * 1024)
if target.is_symlink() or os.path.samefile(resolved_source, target):
raise IngressError(f"Frozen copy must not share the source file: {target}")
target_digest = _sha256(target)
if target_digest != source_digest:
raise IngressError(f"Digest drift while freezing {source.name}")
if target.stat().st_nlink != 1:
raise IngressError(f"Frozen copy has unexpected hard links: {target}")
return target_digest
def _write_new_bytes(path: Path, data: bytes) -> str:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("xb") as handle:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
return hashlib.sha256(data).hexdigest()
def _asset_files(asset_dir: Path | None) -> list[tuple[Path, Path]]:
if asset_dir is None:
return []
root = Path(asset_dir)
if root.is_symlink() or not root.is_dir():
raise IngressError(f"Parser asset directory is not an ordinary directory: {root}")
files: list[tuple[Path, Path]] = []
for path in sorted(root.rglob("*")):
if path.is_symlink():
raise IngressError(f"Parser asset is a symbolic link: {path}")
if path.is_dir():
continue
if not path.is_file():
raise IngressError(f"Parser asset is not an ordinary file: {path}")
files.append((path, path.relative_to(root)))
return files
def _freeze_asset_paths(
blocks: list[dict[str, Any]],
asset_dir: Path | None,
asset_files: list[tuple[Path, Path]],
) -> list[dict[str, Any]]:
"""Rewrite parser-owned asset paths to bundle-relative copied paths."""
frozen = deepcopy(blocks)
if asset_dir is None:
return frozen
root = Path(asset_dir).resolve(strict=True)
by_source = {source.resolve(strict=True): relative for source, relative in asset_files}
by_relative = {relative: relative for _, relative in asset_files}
for index, block in enumerate(frozen):
if not isinstance(block, dict):
continue
kind = str(block.get("type") or block.get("label") or "").lower()
if kind not in {"image", "picture", "drawing", "chart"}:
continue
for key in ("img_path", "path"):
raw = block.get(key)
if not isinstance(raw, str) or not raw.strip():
continue
path = Path(raw)
relative: Path | None = None
if path.is_absolute():
try:
resolved = path.resolve(strict=True)
except FileNotFoundError as exc:
raise IngressError(f"Block {index} asset does not exist: {raw}") from exc
relative = by_source.get(resolved)
elif ".." not in path.parts:
relative = by_relative.get(path)
if relative is None:
candidate = root / path
try:
relative = by_source.get(candidate.resolve(strict=True))
except FileNotFoundError:
relative = None
if relative is None:
raise IngressError(f"Block {index} asset is outside the frozen asset set: {raw}")
block[key] = relative.as_posix()
return frozen
def freeze_document(working_dir: Path, source: Path, parsed: ParsedDocument) -> StagedDocument:
"""Copy one parsed document into an immutable, digest-verified bundle."""
source = Path(source)
canonical_name = source.name
if not canonical_name or canonical_name in {".", ".."}:
raise IngressError(f"Document has no canonical basename: {source}")
pending = pending_root(working_dir)
bundles = bundles_root(working_dir)
pending.mkdir(parents=True, exist_ok=True)
bundles.mkdir(parents=True, exist_ok=True)
staged_source = pending / canonical_name
archived_source = pending / "__parsed__" / canonical_name
final_bundle = bundles / f"{canonical_name}.bundle"
if staged_source.exists() or archived_source.exists() or final_bundle.exists():
raise IngressError(f"Canonical basename already exists in this version: {canonical_name}")
temp_bundle = bundles / f".{canonical_name}.{uuid.uuid4().hex}.tmp"
temp_bundle.mkdir()
try:
asset_files = _asset_files(parsed.asset_dir)
source_digest = _sha256(source.resolve(strict=True))
staged_digest = _copy_regular(source, staged_source)
if source_digest != staged_digest:
raise IngressError(f"Source changed while staging {canonical_name}")
markdown = parsed.markdown.encode("utf-8")
markdown_rel = Path("markdown.utf8")
markdown_digest = _write_new_bytes(temp_bundle / markdown_rel, markdown)
decision = None
blocks_rel: Path | None = None
blocks_digest: str | None = None
frozen_blocks: list[dict[str, Any]] | None = None
if parsed.blocks:
decision = block_policy.prepare_content_list(
parsed.blocks,
engine=parsed.engine,
source_hash=parsed.source_hash,
parser_signature=parsed.parser_signature,
)
frozen_blocks = _freeze_asset_paths(
decision.content_list, parsed.asset_dir, asset_files
)
blocks_rel = Path("blocks.json")
blocks_bytes = json.dumps(
frozen_blocks, ensure_ascii=False, sort_keys=True, separators=(",", ":")
).encode("utf-8")
blocks_digest = _write_new_bytes(temp_bundle / blocks_rel, blocks_bytes)
elif not parsed.markdown.strip():
raise IngressError(f"Parsed document is empty: {canonical_name}")
asset_records: list[dict[str, Any]] = []
for asset, relative in asset_files:
target = temp_bundle / "assets" / relative
digest = _copy_regular(asset, target, allowed_root=Path(parsed.asset_dir))
asset_records.append(
{"path": target.relative_to(temp_bundle).as_posix(), "sha256": digest}
)
kinds = {
str(block.get("type") or block.get("label") or "").lower()
for block in (frozen_blocks or [])
if isinstance(block, dict)
}
modalities = "".join(
flag
for flag, names in (
("i", {"image", "picture", "drawing", "chart"}),
("t", {"table"}),
("e", {"equation", "formula"}),
)
if kinds & names
)
process_options = f"P{modalities}" if frozen_blocks else "F"
chunk_options = (
{"paragraph_semantic": {"chunk_token_size": 1200}}
if frozen_blocks
else {"fixed_token": {}}
)
manifest = {
"parser_bridge_schema": PARSER_BRIDGE_SCHEMA,
"canonical_filename": canonical_name,
"parser": {
"engine": parsed.engine,
"source_hash": parsed.source_hash,
"parser_signature": parsed.parser_signature,
},
"source": {
"path": str(Path("..") / ".." / PENDING_DIRNAME / canonical_name),
"sha256": staged_digest,
},
"markdown": {"path": markdown_rel.as_posix(), "sha256": markdown_digest},
"blocks": (
{"path": blocks_rel.as_posix(), "sha256": blocks_digest}
if blocks_rel is not None
else None
),
"assets": asset_records,
"process_options": process_options,
"chunk_options": chunk_options,
"block_policy": decision.ledger if decision is not None else None,
}
atomic_write_json(temp_bundle / MANIFEST_FILENAME, manifest)
os.replace(temp_bundle, final_bundle)
return StagedDocument(
canonical_name=canonical_name,
source_path=staged_source,
bundle_dir=final_bundle,
manifest_path=final_bundle / MANIFEST_FILENAME,
process_options=process_options,
chunk_options=chunk_options,
audit_ledger=decision.ledger if decision is not None else None,
)
except BaseException:
shutil.rmtree(temp_bundle, ignore_errors=True)
if staged_source.exists() and not staged_source.is_symlink():
staged_source.unlink()
raise
def load_verified_bundle(working_dir: Path, canonical_name: str) -> tuple[dict[str, Any], Path]:
"""Load and digest-verify one published bundle by canonical basename."""
if Path(canonical_name).name != canonical_name or Path(canonical_name).is_absolute():
raise IngressError(f"Invalid canonical basename: {canonical_name!r}")
bundle = bundles_root(working_dir) / f"{canonical_name}.bundle"
manifest_path = bundle / MANIFEST_FILENAME
manifest = json.loads(
_contained_regular_file(bundle, manifest_path, label="manifest").read_text(encoding="utf-8")
)
if (
not isinstance(manifest, dict)
or manifest.get("parser_bridge_schema") != PARSER_BRIDGE_SCHEMA
):
raise IngressError(f"Unsupported parser bridge manifest: {manifest_path}")
if manifest.get("canonical_filename") != canonical_name:
raise IngressError(f"Bundle basename mismatch: {canonical_name}")
records: list[tuple[str, dict[str, Any]]] = []
for key in ("markdown", "blocks"):
record = manifest.get(key)
if record is not None:
if not isinstance(record, dict):
raise IngressError(f"Malformed {key} record in {manifest_path}")
records.append((key, record))
assets = manifest.get("assets")
if not isinstance(assets, list):
raise IngressError(f"Malformed assets record in {manifest_path}")
records.extend(("asset", record) for record in assets if isinstance(record, dict))
if len(records) != 1 + int(manifest.get("blocks") is not None) + len(assets):
raise IngressError(f"Malformed asset entry in {manifest_path}")
for label, record in records:
rel = Path(str(record.get("path") or ""))
if rel.is_absolute() or ".." in rel.parts:
raise IngressError(f"Unsafe {label} path in {manifest_path}")
path = _contained_regular_file(bundle, bundle / rel, label=label)
if _sha256(path) != record.get("sha256"):
raise IngressError(f"Digest mismatch for {label}: {path}")
return manifest, bundle
def remove_unaccepted(staged: StagedDocument) -> None:
"""Remove only a pre-enqueue source/bundle whose doc_status does not exist."""
if staged.source_path.exists() and not staged.source_path.is_symlink():
staged.source_path.unlink()
shutil.rmtree(staged.bundle_dir, ignore_errors=True)
__all__ = [
"BUNDLES_DIRNAME",
"INGRESS_DIRNAME",
"IngressError",
"PARSER_BRIDGE_SCHEMA",
"PENDING_DIRNAME",
"StagedDocument",
"bundles_root",
"freeze_document",
"ingress_root",
"load_verified_bundle",
"pending_root",
"remove_unaccepted",
]
@@ -0,0 +1,99 @@
"""LightRAG parser that consumes frozen DeepTutor ingress bundles."""
from __future__ import annotations
import hashlib
from pathlib import Path
import time
from lightrag.parser.base import BaseParser
from .ingress import IngressError, load_verified_bundle
from .sidecar import build_ir
class DeepTutorParser(BaseParser):
"""Third-party parser registered as ``deeptutor`` in LightRAG rc2."""
engine_name = "deeptutor"
async def parse(self, ctx):
from lightrag.constants import (
FULL_DOCS_FORMAT_LIGHTRAG,
FULL_DOCS_FORMAT_RAW,
)
from lightrag.parser.base import ParseResult
from lightrag.sidecar.writer import write_sidecar
from lightrag.utils import strip_control_characters
from lightrag.utils_pipeline import make_lightrag_doc_content, sidecar_uri_for
resolved = ctx.resolve(self.engine_name)
source = resolved.source_path
if source.is_symlink() or not source.is_file():
raise IngressError(f"Frozen ingress source is not an ordinary file: {source}")
manifest, bundle = load_verified_bundle(Path(ctx.rag.working_dir), resolved.document_name)
digest = hashlib.sha256()
with source.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
source_record = manifest.get("source")
if not isinstance(source_record, dict) or digest.hexdigest() != source_record.get("sha256"):
raise IngressError(f"Frozen source digest mismatch: {resolved.document_name}")
markdown_record = manifest["markdown"]
markdown = strip_control_characters(
(bundle / markdown_record["path"]).read_text(encoding="utf-8")
)
if manifest.get("blocks") is None:
if not markdown.strip():
raise IngressError(f"Frozen RAW document is empty: {resolved.document_name}")
await ctx.rag._persist_parsed_full_docs(
ctx.doc_id,
{
"content": markdown,
"file_path": ctx.file_path,
"parse_format": FULL_DOCS_FORMAT_RAW,
"parse_engine": self.engine_name,
"update_time": int(time.time()),
},
)
await ctx.archive_source(str(source))
return ParseResult(
doc_id=ctx.doc_id,
file_path=ctx.file_path,
parse_format=FULL_DOCS_FORMAT_RAW,
content=markdown,
parse_engine=self.engine_name,
)
ir = build_ir(manifest, bundle)
parsed_data = write_sidecar(
ir,
parsed_dir=resolved.parsed_dir,
doc_id=ctx.doc_id,
engine=self.engine_name,
)
await ctx.rag._persist_parsed_full_docs(
ctx.doc_id,
{
"content": make_lightrag_doc_content(parsed_data["content"]),
"file_path": ctx.file_path,
"parse_format": FULL_DOCS_FORMAT_LIGHTRAG,
"sidecar_location": sidecar_uri_for(resolved.parsed_dir),
"parse_engine": self.engine_name,
"update_time": int(time.time()),
},
)
await ctx.archive_source(str(source))
return ParseResult(
doc_id=ctx.doc_id,
file_path=ctx.file_path,
parse_format=FULL_DOCS_FORMAT_LIGHTRAG,
content=parsed_data["content"],
blocks_path=parsed_data["blocks_path"],
parse_engine=self.engine_name,
)
__all__ = ["DeepTutorParser"]
@@ -1,53 +1,95 @@
"""LightRAG-backed RAG pipeline orchestration.
Implements the same contract as :class:`LlamaIndexPipeline` (see
``..base.RAGPipeline``) but delegates indexing/retrieval to RAG-Anything /
LightRAG. Each KB owns a self-contained LightRAG store under its ``version-N``
directory (see ``storage``).
Documents are turned into a MinerU-style ``content_list`` by DeepTutor's shared
parse layer (``deeptutor/services/parsing``) — the same bridge the question
extractor uses — so multimodal parsing stays a decoupled, cached, engine-
pluggable concern and this pipeline only ever feeds LightRAG ready content.
LightRAG is an optional dependency: every method fails with a clear, actionable
message when it is not installed instead of an opaque ``ImportError``.
"""
"""DeepTutor orchestration for the LightRAG 1.5 native document pipeline."""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from dataclasses import dataclass, field, replace
import logging
from pathlib import Path
import shutil
import traceback
from typing import Any, Dict, List, Optional
from typing import Any, Callable, Dict, List, Optional
from deeptutor.runtime.home import get_runtime_data_root
from deeptutor.services.rag.index_versioning import (
list_kb_versions,
resolve_storage_dir_for_read,
resolve_storage_dir_for_rebuild,
)
from deeptutor.services.rag.kb_paths import resolve_kb_dir
from . import block_policy, engine, storage
from . import block_policy, engine, ingress, storage
from . import config as lr_config
from .worker import OwnerLoopBridge, run_in_worker_loop
logger = logging.getLogger(__name__)
DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")
class LightRagPipeline:
"""Index/retrieve KB content via RAG-Anything / LightRAG."""
@dataclass(frozen=True)
class BatchOutcome:
requested: int
preflight_failed: dict[str, str] = field(default_factory=dict)
accepted: int = 0
processed: tuple[str, ...] = ()
failed: dict[str, str] = field(default_factory=dict)
nonterminal: dict[str, str] = field(default_factory=dict)
missing: tuple[str, ...] = ()
track_id: str = ""
@property
def complete(self) -> bool:
return (
self.requested > 0
and len(self.processed) == self.requested
and not self.preflight_failed
and not self.failed
and not self.nonterminal
and not self.missing
)
class LightRagBatchError(RuntimeError):
def __init__(self, outcome: BatchOutcome) -> None:
self.outcome = outcome
failures = {**outcome.preflight_failed, **outcome.failed}
detail = "; ".join(f"{name}: {error}" for name, error in sorted(failures.items()))
message = (
f"LightRAG batch incomplete: added {len(outcome.processed)}, "
f"failed {len(failures)}, missing {len(outcome.missing)}, "
f"nonterminal {len(outcome.nonterminal)}"
)
super().__init__(f"{message}: {detail}" if detail else message)
class LightRagNeedsReindexError(RuntimeError):
"""Raised when an append targets a pre-native LightRAG index."""
def _status_text(row: Any) -> str:
status = getattr(row, "status", None)
value = getattr(status, "value", status)
return str(value or "").strip().lower()
def _row_name(row: Any) -> str:
return Path(str(getattr(row, "file_path", "") or "")).name
def _row_error(row: Any) -> str:
for key in ("error_msg", "error"):
value = getattr(row, key, None)
if isinstance(value, str) and value.strip():
return value.strip()
return _status_text(row) or "unknown LightRAG failure"
class LightRagPipeline:
def __init__(self, kb_base_dir: Optional[str] = None, **_: Any) -> None:
self.logger = logging.getLogger(__name__)
self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIR
# ----- helpers --------------------------------------------------------
self._status_poll_seconds = 0.2
self._status_no_progress_seconds = 600.0
def _ensure_available(self) -> None:
if not lr_config.is_lightrag_available():
@@ -68,265 +110,326 @@ class LightRagPipeline:
default=lr_config.DEFAULT_MODE,
)
def _cleanup_failed_version_dir(self, root_dir: Path) -> None:
try:
if root_dir.is_dir() and not (root_dir / storage.META_FILENAME).exists():
shutil.rmtree(root_dir)
except Exception as exc: # pragma: no cover - best-effort
self.logger.warning("Could not clean up failed version dir %s: %s", root_dir, exc)
async def _ingest(
self,
rag: Any,
file_paths: List[str],
*,
io_bridge: OwnerLoopBridge,
progress_callback: Callable[[int, int], Any] | None = None,
) -> int:
"""Parse each file via the shared parse layer and insert it into LightRAG.
Returns the number of documents successfully inserted. Per-file failures
are logged and skipped so one bad document doesn't abort the batch.
"""
from deeptutor.services.parsing import ParserError, get_parse_service
def _stage_documents(
self, working_dir: Path, file_paths: List[str]
) -> tuple[list[ingress.StagedDocument], dict[str, str]]:
from deeptutor.services.parsing import get_parse_service
parse_service = get_parse_service()
inserted = 0
total = len(file_paths)
for file_path in file_paths:
io_bridge.raise_if_cancelled()
path = Path(file_path)
staged: list[ingress.StagedDocument] = []
failures: dict[str, str] = {}
seen: set[str] = set()
vision_available = lr_config.vision_model_available()
for raw_path in file_paths:
path = Path(raw_path)
name = path.name
if name in seen:
failures[name] = "duplicate canonical basename in request"
continue
seen.add(name)
try:
doc = parse_service.parse(path)
except ParserError as exc:
self.logger.warning("LightRAG: parse failed for %s: %s", path.name, exc)
continue
parsed = parse_service.parse(path)
item = ingress.freeze_document(working_dir, path, parsed)
if "i" in item.process_options and not vision_available:
item = replace(item, process_options=item.process_options.replace("i", ""))
staged.append(item)
except Exception as exc:
failures[name or str(path)] = str(exc)
return staged, failures
accepted_ledger: dict[str, Any] | None = None
attempt_id: str | None = None
if doc.blocks:
document_id = doc.source_hash or path.stem
decision = block_policy.prepare_content_list(
doc.blocks,
engine=doc.engine,
source_hash=doc.source_hash,
parser_signature=doc.parser_signature,
)
if decision.ledger is not None:
outcome = "unknown_types" if decision.unknown_type_counts else "accepted"
_, attempt_id = block_policy.write_attempt_ledger(
Path(rag.working_dir).parent,
document_id,
decision.ledger,
outcome=outcome,
)
counts = decision.ledger["counts"]
self.logger.info(
"MinerU block policy %s raw=%d filtered=%d eligible=%d unknown=%d",
block_policy.POLICY_ID,
counts["raw_total"],
counts["filtered_total"],
counts["eligible_total"],
counts["unknown_total"],
)
if decision.unknown_type_counts:
# Indexed, not dropped and not fatal — say so, because
# this is the signal that the policy needs a new entry.
self.logger.warning(
"LightRAG: %s has MinerU block types with no policy "
"entry (%s); indexing them unclassified",
path.name,
decision.unknown_summary(),
)
accepted_ledger = decision.ledger
content_list = decision.content_list
else:
content_list = (
[{"type": "text", "text": doc.markdown, "page_idx": 0}] if doc.markdown else []
)
if not content_list:
self.logger.warning("LightRAG: empty document skipped: %s", path.name)
continue
await engine.insert(
rag,
content_list,
file_name=path.name,
doc_id=doc.source_hash or path.stem,
)
async def _reconcile(
self,
rag: Any,
staged: list[ingress.StagedDocument],
preflight_failed: dict[str, str],
track_id: str,
io_bridge: OwnerLoopBridge,
progress_callback: Callable[[int, int], Any] | None,
) -> BatchOutcome:
expected = {item.canonical_name: item for item in staged}
last_snapshot: tuple[tuple[str, str], ...] | None = None
last_progress = asyncio.get_running_loop().time()
terminal_count = 0
while True:
io_bridge.raise_if_cancelled()
doc_error = storage.document_error(Path(rag.working_dir), doc.source_hash or path.stem)
if doc_error:
raise RuntimeError(f"{path.name}: {doc_error}")
if accepted_ledger is not None:
block_policy.write_decision_ledger(
Path(rag.working_dir),
doc.source_hash or path.stem,
accepted_ledger,
attempt_id=attempt_id,
rows = await rag.aget_docs_by_track_id(track_id)
if not isinstance(rows, dict):
raise engine.LightRagContractError("aget_docs_by_track_id must return an object")
by_name: dict[str, tuple[str, Any]] = {}
duplicates: set[str] = set()
for doc_id, row in rows.items():
name = _row_name(row)
if name in by_name:
duplicates.add(name)
by_name[name] = (str(doc_id), row)
if duplicates:
raise engine.LightRagContractError(
f"track_id returned duplicate canonical basenames: {sorted(duplicates)}"
)
inserted += 1
self.logger.info("LightRAG: inserted %s", path.name)
if progress_callback is not None:
await io_bridge.call(progress_callback, inserted, total)
return inserted
snapshot = tuple(
sorted((name, _status_text(row)) for name, (_, row) in by_name.items())
)
if snapshot != last_snapshot:
last_snapshot = snapshot
last_progress = asyncio.get_running_loop().time()
processed = tuple(
sorted(
name
for name, (_, row) in by_name.items()
if name in expected and _status_text(row) == "processed"
)
)
failed = {
name: _row_error(row)
for name, (_, row) in by_name.items()
if name in expected and _status_text(row) == "failed"
}
unknown = {
name: _status_text(row)
for name, (_, row) in by_name.items()
if name in expected
and _status_text(row)
not in {
"pending",
"parsing",
"analyzing",
"processing",
"preprocessed",
"processed",
"failed",
}
}
active = {
name: _status_text(row)
for name, (_, row) in by_name.items()
if name in expected
and _status_text(row)
in {"pending", "parsing", "analyzing", "processing", "preprocessed"}
}
missing = tuple(sorted(set(expected) - set(by_name)))
current_terminal = len(processed) + len(failed)
if progress_callback is not None and current_terminal != terminal_count:
terminal_count = current_terminal
await io_bridge.call(
progress_callback, terminal_count, len(expected) + len(preflight_failed)
)
if not active and not missing:
outcome = BatchOutcome(
requested=len(expected) + len(preflight_failed),
preflight_failed=preflight_failed,
accepted=len(expected),
processed=processed,
failed=failed,
nonterminal=unknown,
missing=(),
track_id=track_id,
)
for name in processed:
item = expected[name]
if item.audit_ledger is not None:
doc_id = by_name[name][0]
block_policy.write_decision_ledger(
Path(rag.working_dir), doc_id, item.audit_ledger
)
return outcome
if unknown:
return BatchOutcome(
requested=len(expected) + len(preflight_failed),
preflight_failed=preflight_failed,
accepted=len(expected),
processed=processed,
failed=failed,
nonterminal=unknown,
missing=missing,
track_id=track_id,
)
if (
asyncio.get_running_loop().time() - last_progress
>= self._status_no_progress_seconds
):
return BatchOutcome(
requested=len(expected) + len(preflight_failed),
preflight_failed=preflight_failed,
accepted=len(expected),
processed=processed,
failed=failed,
nonterminal=active,
missing=missing,
track_id=track_id,
)
await asyncio.sleep(self._status_poll_seconds)
async def _run_indexing(
self,
working_dir: Path,
file_paths: List[str],
progress_callback: Callable[[int, int], Any] | None,
) -> int:
"""Run the complete local LightRAG indexing phase off the service loop.
The RAG instance is constructed and consumed in one worker thread, so
its mutable stores and asyncio primitives never cross event loops.
DeepTutor-owned network calls and progress callbacks cross back through
``OwnerLoopBridge`` and remain responsive while local JSON storage is
busy in the worker.
"""
async def job(io_bridge: OwnerLoopBridge) -> int:
) -> BatchOutcome:
async def job(io_bridge: OwnerLoopBridge) -> BatchOutcome:
io_bridge.raise_if_cancelled()
rag = engine.build_rag(working_dir, io_bridge=io_bridge)
failed = True
try:
result = await self._ingest(
rag,
file_paths,
io_bridge=io_bridge,
progress_callback=progress_callback,
staged, preflight_failed = self._stage_documents(working_dir, file_paths)
if not staged:
raise LightRagBatchError(
BatchOutcome(requested=len(file_paths), preflight_failed=preflight_failed)
)
try:
rag = engine.build_rag(
working_dir,
io_bridge=io_bridge,
enable_vlm=any("i" in item.process_options for item in staged),
)
except BaseException:
for item in staged:
ingress.remove_unaccepted(item)
raise
failed = True
accepted = False
enqueue_started = False
cleanup: list[ingress.StagedDocument] = []
try:
await engine.initialize(rag)
enqueue_started = True
track_id = await engine.enqueue(rag, staged)
if not isinstance(track_id, str) or not track_id.strip():
raise engine.LightRagContractError(
"LightRAG enqueue did not return a valid track_id"
)
accepted = True
await rag.apipeline_process_enqueue_documents()
outcome = await self._reconcile(
rag,
staged,
preflight_failed,
track_id,
io_bridge,
progress_callback,
)
if not outcome.complete:
raise LightRagBatchError(outcome)
failed = False
return result
return outcome
except BaseException:
if not enqueue_started:
cleanup = staged
elif not accepted:
try:
cleanup = await engine.confirmed_unaccepted(rag, staged)
except BaseException:
self.logger.exception(
"Could not confirm which LightRAG documents were rejected; "
"retaining all staged ingress"
)
raise
finally:
try:
await engine.finalize(rag, cancel_pending=failed)
except BaseException:
if not failed:
raise
self.logger.exception(
"LightRAG resource cleanup failed while indexing was aborting"
)
self.logger.exception("LightRAG cleanup failed while indexing was aborting")
finally:
for item in cleanup:
ingress.remove_unaccepted(item)
return await run_in_worker_loop(job)
# ----- indexing -------------------------------------------------------
def _remove_zero_accepted_candidate(self, root_dir: Path) -> None:
if not root_dir.is_dir() or storage.has_any_doc_status(root_dir):
return
for ingress_dir in (ingress.pending_root(root_dir), ingress.bundles_root(root_dir)):
if ingress_dir.is_dir() and any(path.is_file() for path in ingress_dir.rglob("*")):
return
shutil.rmtree(root_dir)
async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
self._ensure_available()
progress_callback = kwargs.get("progress_callback")
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)
self.logger.info(
"Initializing KB '%s' with %d file(s) using LightRAG", kb_name, len(file_paths)
)
try:
count = await self._run_indexing(
storage.working_dir(root_dir), file_paths, progress_callback
outcome = await self._run_indexing(
root_dir, file_paths, kwargs.get("progress_callback")
)
if count == 0:
self.logger.error("LightRAG: no extractable documents for '%s'", kb_name)
self._cleanup_failed_version_dir(root_dir)
return False
if not storage.has_output(root_dir):
details = storage.failure_summary(root_dir)
message = f"LightRAG did not produce a ready index for '{kb_name}'"
if details:
message = f"{message}: {details}"
self.logger.error(message)
self._cleanup_failed_version_dir(root_dir)
raise RuntimeError(message)
raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")
storage.write_meta(root_dir)
self.logger.info("KB '%s' initialized with LightRAG (%d docs)", kb_name, count)
return True
return outcome.complete
except asyncio.CancelledError:
self._cleanup_failed_version_dir(root_dir)
raise
except Exception as exc:
self.logger.error("Failed to initialize LightRAG KB: %s", exc)
self.logger.error(traceback.format_exc())
self._cleanup_failed_version_dir(root_dir)
except LightRagBatchError as exc:
if exc.outcome.accepted == 0:
self._remove_zero_accepted_candidate(root_dir)
raise
except Exception:
self._remove_zero_accepted_candidate(root_dir)
raise
async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
self._ensure_available()
progress_callback = kwargs.get("progress_callback")
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
existing = resolve_storage_dir_for_read(kb_dir, None)
if existing is not None and storage.has_output(existing):
is_update = True
if existing is not None and storage.meta_is_native_published(existing):
root_dir = existing
is_update = True
elif existing is not None or list_kb_versions(kb_dir):
raise LightRagNeedsReindexError(
"This LightRAG index is legacy, unpublished, or corrupt and must be rebuilt "
"before appending."
)
else:
root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)
is_update = False
root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)
self.logger.info(
"Adding %d document(s) to LightRAG KB '%s' (update=%s)",
len(file_paths),
kb_name,
is_update,
)
try:
count = await self._run_indexing(
storage.working_dir(root_dir), file_paths, progress_callback
outcome = await self._run_indexing(
root_dir, file_paths, kwargs.get("progress_callback")
)
if count == 0:
self.logger.warning("LightRAG: no extractable documents to add for '%s'", kb_name)
return False
if not storage.has_output(root_dir):
details = storage.failure_summary(root_dir)
message = f"LightRAG did not produce a ready index for '{kb_name}'"
if details:
message = f"{message}: {details}"
self.logger.error(message)
if not is_update:
self._cleanup_failed_version_dir(root_dir)
raise RuntimeError(message)
raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")
storage.write_meta(root_dir)
self.logger.info("Added %d doc(s) to LightRAG KB '%s'", count, kb_name)
return True
except asyncio.CancelledError:
if not is_update:
self._cleanup_failed_version_dir(root_dir)
return outcome.complete
except LightRagBatchError as exc:
if not is_update and exc.outcome.accepted == 0:
self._remove_zero_accepted_candidate(root_dir)
raise
except Exception as exc:
self.logger.error("Failed to add documents to LightRAG KB: %s", exc)
self.logger.error(traceback.format_exc())
except Exception:
if not is_update:
self._cleanup_failed_version_dir(root_dir)
self._remove_zero_accepted_candidate(root_dir)
raise
# ----- retrieval ------------------------------------------------------
async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
root_dir = resolve_storage_dir_for_read(kb_dir, None)
if root_dir is None or not storage.has_output(root_dir):
if root_dir is None or not storage.meta_is_native_published(root_dir):
return {
"query": query,
"answer": (
"This LightRAG knowledge base has no index yet. Add documents before querying."
),
"answer": "This LightRAG knowledge base must be rebuilt for the native pipeline.",
"content": "",
"sources": [],
"provider": storage.PROVIDER,
"needs_reindex": True,
}
mode = self._resolve_mode(kb_name, kwargs)
try:
self._ensure_available()
rag = engine.build_rag(storage.working_dir(root_dir))
answer, sources = await engine.query_with_sources(rag, query, mode)
async def job(io_bridge: OwnerLoopBridge):
rag = engine.build_rag(root_dir, io_bridge=io_bridge)
failed = True
try:
await engine.initialize(rag)
result = await engine.query_with_sources(rag, query, mode)
failed = False
return result
finally:
await engine.finalize(rag, cancel_pending=failed)
answer, sources = await run_in_worker_loop(job)
except lr_config.LightRagNotAvailableError as exc:
return self._error_result(query, exc, error_type="not_configured")
except Exception as exc:
self.logger.error("LightRAG search failed: %s", exc)
self.logger.error(traceback.format_exc())
return self._error_result(query, exc, error_type="retrieval_error")
return {
"query": query,
"answer": answer,
@@ -346,15 +449,17 @@ class LightRagPipeline:
"error_type": error_type,
}
# ----- lifecycle ------------------------------------------------------
async def delete(self, kb_name: str, **kwargs) -> bool:
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
if kb_dir.exists():
shutil.rmtree(kb_dir)
self.logger.info("Deleted LightRAG KB '%s'", kb_name)
return True
return False
__all__ = ["LightRagPipeline"]
__all__ = [
"BatchOutcome",
"LightRagBatchError",
"LightRagNeedsReindexError",
"LightRagPipeline",
]
@@ -0,0 +1,320 @@
"""Map frozen DeepTutor MinerU blocks to LightRAG's public Sidecar IR."""
from __future__ import annotations
import json
from pathlib import Path
import re
from typing import Any
class SidecarMappingError(ValueError):
"""Raised when a structured block cannot be represented without data loss."""
def _text(item: dict[str, Any]) -> str:
for key in ("text", "content", "body", "code_body"):
value = item.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return ""
def _strings(value: Any) -> list[str]:
if isinstance(value, list):
return [str(item).strip() for item in value if str(item).strip()]
value = str(value or "").strip()
return [value] if value else []
def _position(item: dict[str, Any]):
from lightrag.sidecar.ir import IRPosition
page = item.get("page_idx", item.get("page"))
if isinstance(page, bool):
page = None
elif isinstance(page, int):
page = str(page + 1) if page >= 0 else str(page)
elif page is not None:
page = str(page).strip() or None
bbox = item.get("bbox")
if isinstance(bbox, (list, tuple)) and len(bbox) >= 4:
try:
return IRPosition(type="bbox", anchor=page, range=[float(value) for value in bbox[:4]])
except (TypeError, ValueError):
pass
return IRPosition(type="bbox", anchor=page) if page is not None else None
def _heading(item: dict[str, Any], kind: str) -> tuple[str, int]:
level = item.get("text_level", item.get("level", 0))
try:
level = int(level or 0)
except (TypeError, ValueError):
level = 0
if kind in {"title", "section_header"}:
return _text(item), max(level, 1)
if kind == "text" and level > 0:
return _text(item), level
return "", 0
def _rows(value: Any) -> list[list[str]] | None:
if isinstance(value, str):
stripped = value.strip()
if stripped.startswith("["):
try:
value = json.loads(stripped)
except json.JSONDecodeError:
return None
else:
return None
if not isinstance(value, list):
return None
rows: list[list[str]] = []
for raw_row in value:
if not isinstance(raw_row, list):
continue
rows.append(
[
str(cell.get("text", "")).strip() if isinstance(cell, dict) else str(cell).strip()
for cell in raw_row
]
)
return rows or None
def _caption(item: dict[str, Any], *keys: str) -> str:
direct = str(item.get("caption") or "").strip()
if direct:
return direct
for key in keys:
values = _strings(item.get(key))
if values:
return values[0]
return ""
def _resolve_asset(bundle: Path, manifest: dict[str, Any], raw: str) -> Path | None:
if not raw:
return None
relative = Path(raw)
if relative.is_absolute() or ".." in relative.parts:
raise SidecarMappingError(f"Asset path escapes the frozen bundle: {raw}")
candidates: list[Path] = []
direct = bundle / "assets" / relative
if direct.is_file():
candidates.append(direct)
basename = relative.name
for record in manifest.get("assets", []):
path = bundle / str(record.get("path") or "")
if path.name == basename and path.is_file() and path not in candidates:
candidates.append(path)
if len(candidates) > 1:
raise SidecarMappingError(f"Asset basename is ambiguous in the frozen bundle: {raw}")
return candidates[0] if candidates else None
def build_ir(manifest: dict[str, Any], bundle: Path):
"""Return an ``IRDoc`` using only LightRAG's public Sidecar types."""
from lightrag.sidecar.ir import (
AssetSpec,
IRBlock,
IRDoc,
IRDrawing,
IREquation,
IRTable,
)
blocks_record = manifest.get("blocks")
if not isinstance(blocks_record, dict):
raise SidecarMappingError("Sidecar mapping requires a blocks payload")
raw_blocks = json.loads((bundle / blocks_record["path"]).read_text(encoding="utf-8"))
if not isinstance(raw_blocks, list):
raise SidecarMappingError("Frozen blocks payload is not an array")
output: list[Any] = []
assets: list[Any] = []
asset_refs: dict[Path, str] = {}
heading_stack: list[str] = []
current_lines: list[str] = []
current_tables: list[Any] = []
current_drawings: list[Any] = []
current_equations: list[Any] = []
current_positions: list[Any] = []
current_heading = "Preface/Uncategorized"
current_level = 0
current_parents: list[str] = []
sequence = 0
document_title = ""
def next_key(prefix: str) -> str:
nonlocal sequence
sequence += 1
return f"{prefix}{sequence}"
def flush() -> None:
nonlocal \
current_lines, \
current_tables, \
current_drawings, \
current_equations, \
current_positions
content = "\n".join(line for line in current_lines if line).strip()
if not content and not (current_tables or current_drawings or current_equations):
current_lines = []
current_positions = []
return
output.append(
IRBlock(
content_template=content,
heading=current_heading,
level=current_level,
parent_headings=list(current_parents),
positions=list(current_positions),
tables=list(current_tables),
drawings=list(current_drawings),
equations=list(current_equations),
)
)
current_lines = []
current_tables = []
current_drawings = []
current_equations = []
current_positions = []
for index, item in enumerate(raw_blocks):
if not isinstance(item, dict):
raise SidecarMappingError(f"Structured block {index} is not an object")
kind = str(item.get("type") or item.get("label") or "").strip().lower()
heading, level = _heading(item, kind)
position = _position(item)
if heading:
flush()
heading = re.sub(r"^#{1,6}\s+", "", heading).strip()
heading_stack = heading_stack[: max(level - 1, 0)]
current_parents = [value for value in heading_stack if value]
heading_stack.append(heading)
current_heading = heading
current_level = level
current_lines.append(f"{'#' * min(level, 6)} {heading}")
if position is not None:
current_positions.append(position)
if not document_title and level == 1:
document_title = heading
continue
if kind in {"text", "aside_text", "page_footnote"}:
value = _text(item)
if value:
current_lines.append(value)
elif kind == "list":
values = item.get("list_items")
value = "\n".join(_strings(values)) if isinstance(values, list) else _text(item)
if value:
current_lines.append(value)
elif kind == "code":
value = str(item.get("code_body") or _text(item)).strip()
if value:
current_lines.extend(_strings(item.get("code_caption")))
current_lines.append(value)
current_lines.extend(_strings(item.get("code_footnote")))
elif kind == "table":
body = item.get("rows", item.get("table_body"))
table_rows = _rows(body)
table_html = (
body.strip() if isinstance(body, str) and "<table" in body.lower() else None
)
if not table_rows and not table_html:
raise SidecarMappingError(f"Structured table {index} has no usable body")
key = next_key("tb")
current_tables.append(
IRTable(
placeholder_key=key,
rows=table_rows,
html=table_html,
num_rows=int(item.get("num_rows") or (len(table_rows) if table_rows else 0)),
num_cols=int(
item.get("num_cols") or (max(map(len, table_rows)) if table_rows else 0)
),
caption=_caption(item, "table_caption"),
footnotes=_strings(item.get("table_footnote") or item.get("footnotes")),
table_header=_rows(item.get("header")),
self_ref=f"blocks.json#/{index}",
)
)
current_lines.append(f"{{{{TBL:{key}}}}}")
elif kind in {"image", "picture", "drawing", "chart"}:
raw_path = str(item.get("img_path") or item.get("path") or "")
asset_path = _resolve_asset(bundle, manifest, raw_path)
if asset_path is None:
raise SidecarMappingError(f"Structured {kind} {index} has no verified bundle asset")
ref = ""
ref = asset_refs.get(asset_path, "")
if not ref:
ref = f"asset-{len(asset_refs) + 1}"
asset_refs[asset_path] = ref
assets.append(AssetSpec(ref=ref, suggested_name=asset_path.name, source=asset_path))
key = next_key("im")
current_drawings.append(
IRDrawing(
placeholder_key=key,
asset_ref=ref,
fmt=Path(raw_path).suffix.lower().lstrip(".") or str(item.get("format") or ""),
caption=_caption(item, "image_caption", "chart_caption", "captions"),
footnotes=_strings(
item.get("image_footnote")
or item.get("chart_footnote")
or item.get("footnotes")
),
src=str(item.get("src") or ""),
self_ref=f"blocks.json#/{index}",
)
)
current_lines.append(f"{{{{IMG:{key}}}}}")
elif kind in {"equation", "formula"}:
latex = _text(item)
if not latex:
raise SidecarMappingError(f"Structured equation {index} has no LaTeX")
key = next_key("eq")
inline = str(item.get("text_format") or "").lower() in {"inline", "inline_equation"}
current_equations.append(
IREquation(
placeholder_key=key,
latex=latex,
is_block=not inline,
caption=_caption(item, "equation_caption"),
footnotes=_strings(item.get("equation_footnote") or item.get("footnotes")),
self_ref=f"blocks.json#/{index}" if not inline else "",
)
)
current_lines.append(f"{{{{{'EQI' if inline else 'EQ'}:{key}}}}}")
else:
value = _text(item)
if not value:
raise SidecarMappingError(
f"Unknown structured block type {kind or '<missing>'!r} at {index} has no preservable text"
)
current_lines.append(value)
if position is not None:
current_positions.append(position)
flush()
if not output:
raise SidecarMappingError("Structured document produced no Sidecar blocks")
name = str(manifest.get("canonical_filename") or "document")
return IRDoc(
document_name=name,
document_format=Path(name).suffix.lower().lstrip("."),
doc_title=document_title or Path(name).stem,
split_option={
"parser": str((manifest.get("parser") or {}).get("engine") or ""),
"parser_signature": str((manifest.get("parser") or {}).get("parser_signature") or ""),
},
blocks=output,
assets=assets,
bbox_attributes={"origin": "LEFTTOP", "max": 1000},
)
__all__ = ["SidecarMappingError", "build_ir"]
@@ -31,6 +31,8 @@ logger = logging.getLogger(__name__)
META_FILENAME = "meta.json"
PROVIDER = "lightrag"
ADAPTER_SCHEMA = 2
PUBLISHED_STATE = "published"
# Glob patterns LightRAG writes once it has actually built chunk/vector data.
# A graphml file alone is not enough: LightRAG creates an empty graph at startup
@@ -46,11 +48,26 @@ def working_dir(root_dir: Path) -> Path:
return Path(root_dir)
def _store_root(root_dir: Path) -> Path:
"""Resolve native workspace storage while retaining legacy flat reads."""
root = Path(root_dir)
if (root / _DOC_STATUS_FILENAME).exists() or any(root.glob("vdb_*.json")):
return root
meta = _read_meta(root)
workspace = str((meta or {}).get("workspace") or "").strip()
if not workspace:
from .engine import workspace_for
workspace = workspace_for(root)
candidate = root / workspace
return candidate if candidate.is_dir() else root
def has_output(root_dir: Path | None) -> bool:
"""True when LightRAG has at least one successfully indexed document."""
if root_dir is None:
return False
root = Path(root_dir)
root = _store_root(Path(root_dir))
if not root.is_dir():
return False
@@ -93,7 +110,7 @@ def failure_summary(root_dir: Path | None, *, limit: int = 3) -> str:
"""Return a short human-readable summary of failed LightRAG documents."""
if root_dir is None:
return ""
payload = _read_doc_status(Path(root_dir))
payload = _read_doc_status(_store_root(Path(root_dir)))
if not payload:
return ""
@@ -116,7 +133,7 @@ def document_error(root_dir: Path | None, doc_id: str) -> str:
"""Return the stored LightRAG error for one document, if present."""
if root_dir is None or not doc_id:
return ""
payload = _read_doc_status(Path(root_dir))
payload = _read_doc_status(_store_root(Path(root_dir)))
if not payload:
return ""
item = payload.get(doc_id)
@@ -142,6 +159,58 @@ def _read_doc_status(root_dir: Path) -> dict[str, Any] | None:
return None
def has_any_doc_status(root_dir: Path | None) -> bool:
if root_dir is None:
return False
payload = _read_doc_status(_store_root(Path(root_dir)))
return bool(payload)
def _read_meta(root_dir: Path) -> dict[str, Any] | None:
path = Path(root_dir) / META_FILENAME
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
return payload if isinstance(payload, dict) else None
def meta_is_native_published(root_dir: Path | None) -> bool:
if root_dir is None:
return False
meta = _read_meta(Path(root_dir))
return bool(
meta
and meta.get("provider") == PROVIDER
and meta.get("signature") == PROVIDER
and meta.get("lightrag_adapter_schema") == ADAPTER_SCHEMA
and meta.get("parser_bridge_schema") == 1
and meta.get("state") == PUBLISHED_STATE
and has_output(Path(root_dir))
)
def _parser_inputs(root_dir: Path) -> list[dict[str, str]]:
from .ingress import bundles_root, load_verified_bundle
records: set[tuple[str, str]] = set()
for bundle in sorted(bundles_root(root_dir).glob("*.bundle")):
canonical_name = bundle.name.removesuffix(".bundle")
manifest, _ = load_verified_bundle(root_dir, canonical_name)
parser = manifest.get("parser")
if not isinstance(parser, dict):
continue
records.add(
(
str(parser.get("engine") or ""),
str(parser.get("parser_signature") or ""),
)
)
return [
{"engine": engine, "parser_signature": signature} for engine, signature in sorted(records)
]
def write_meta(root_dir: Path) -> None:
"""Write a flat-layout ``meta.json`` so the version lists as ready.
@@ -153,13 +222,24 @@ def write_meta(root_dir: Path) -> None:
"""
from deeptutor.services.rag.embedding_signature import embedding_meta_fields
from .engine import installed_version, workspace_for
target = Path(root_dir)
previous = _read_meta(target) or {}
now = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
payload = {
"version": target.name,
"signature": PROVIDER,
"provider": PROVIDER,
"state": PUBLISHED_STATE,
"lightrag_adapter_schema": ADAPTER_SCHEMA,
"lightrag_package_version": installed_version(),
"parser_bridge_schema": 1,
"parser_inputs": _parser_inputs(target),
"workspace": workspace_for(target),
"layout": "flat",
"created_at": datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",
"created_at": str(previous.get("created_at") or now),
"updated_at": now,
**embedding_meta_fields(),
}
atomic_write_json(target / META_FILENAME, payload)
@@ -170,7 +250,9 @@ __all__ = [
"PROVIDER",
"document_error",
"failure_summary",
"has_any_doc_status",
"working_dir",
"has_output",
"meta_is_native_published",
"write_meta",
]
@@ -1,6 +1,6 @@
"""Event-loop isolation helpers for local LightRAG indexing.
RAG-Anything's local storage backends perform synchronous graph merging and
LightRAG's local storage backends perform synchronous graph merging and
JSON serialization from inside async methods. Running those methods on the
service event loop therefore stalls unrelated API and LLM work. This module
provides one narrow boundary: run the indexing coroutine on a worker thread's
@@ -79,8 +79,16 @@ class LlamaIndexDocumentLoader:
# archive download) on a synchronous httpx.Client — running it on
# the event loop stalls every other request for the whole PDF
# (same class of bug as upstream #761/#777). Hand it to a thread.
text, extracted_images = await asyncio.to_thread(self._parse_document, file_path)
self._append_if_nonempty(documents, file_path, text)
text, extracted_images, parse_engine = await asyncio.to_thread(
self._parse_document, file_path
)
self._append_if_nonempty(
documents,
file_path,
text,
parse_engine=parse_engine,
extracted_image_count=len(extracted_images),
)
image_sources.extend(extracted_images)
for file_path_str in classification.text_files:
@@ -105,10 +113,10 @@ class LlamaIndexDocumentLoader:
return documents
def _parse_document(self, file_path: Path) -> tuple[str, list[_ImageSource]]:
def _parse_document(self, file_path: Path) -> tuple[str, list[_ImageSource], str]:
"""Parse a document through the shared, engine-pluggable parse layer.
Returns ``(text, extracted_images)``. A parse failure (engine
Returns ``(text, extracted_images, engine)``. A parse failure (engine
unavailable, unsupported format for the active engine, or models not
ready) is logged and the file is skipped — matching the sibling
LightRAG/GraphRAG pipelines — rather than aborting the whole batch.
@@ -122,11 +130,11 @@ class LlamaIndexDocumentLoader:
f"Skipped {file_path.name}: the active document-parsing engine could "
f"not handle it ({exc}). Change the engine in Settings → Document Parsing."
)
return "", []
return "", [], ""
text = parsed.markdown.strip() or self._text_from_blocks(parsed.blocks)
images = self._collect_asset_images(parsed.asset_dir, origin=file_path)
return text, images
return text, images, str(parsed.engine or "")
@staticmethod
def _text_from_blocks(blocks: list[dict] | None) -> str:
@@ -338,7 +346,15 @@ class LlamaIndexDocumentLoader:
"mimetype": mimetype,
}
def _append_if_nonempty(self, documents: list[Any], file_path: Path, text: str) -> None:
def _append_if_nonempty(
self,
documents: list[Any],
file_path: Path,
text: str,
*,
parse_engine: str = "",
extracted_image_count: int = 0,
) -> None:
if text.strip():
documents.append(
Document(
@@ -351,4 +367,16 @@ class LlamaIndexDocumentLoader:
)
self.logger.info(f"Loaded: {file_path.name} ({len(text)} chars)")
else:
self.logger.warning(f"Skipped empty document: {file_path.name}")
if file_path.suffix.lower() == ".pdf" and extracted_image_count:
engine_label = parse_engine or "the active parser"
self.logger.warning(
"Skipped empty document: %s. The %s engine extracted %d image(s) "
"but no text. This is usually a scanned PDF; use an OCR-capable "
"parsing engine such as MinerU or Docling with OCR enabled. "
"Change the engine in Settings, Document Parsing.",
file_path.name,
engine_label,
extracted_image_count,
)
else:
self.logger.warning(f"Skipped empty document: {file_path.name}")
+13 -4
View File
@@ -147,10 +147,19 @@ def _graphrag_preflight() -> dict:
def _lightrag_preflight() -> dict:
package_detail = "pip install 'deeptutor[rag-lightrag]'"
try:
from .pipelines.lightrag.config import is_lightrag_available
from .pipelines.lightrag.engine import LIGHTRAG_VERSION, installed_version
installed = is_lightrag_available()
current_version = installed_version() if is_lightrag_available() else ""
installed = current_version == LIGHTRAG_VERSION
if current_version:
package_detail = (
f"Installed {current_version}."
if installed
else f"Found {current_version}; required {LIGHTRAG_VERSION}."
)
except Exception:
installed = False
emb_model, emb_dim = _active_embedding()
@@ -167,9 +176,9 @@ def _lightrag_preflight() -> dict:
[
_check(
"package",
"RAG-Anything package installed",
"LightRAG package installed",
installed,
"Installed." if installed else "pip install 'deeptutor[rag-lightrag]'",
package_detail,
),
_check(
"chat",
@@ -189,7 +198,7 @@ def _lightrag_preflight() -> dict:
vision_ok,
"Active chat model supports vision."
if vision_ok
else "Active chat model has no vision — multimodal documents fall back to text.",
else "Active chat model has no vision — image analysis is disabled.",
optional=True,
),
]
+1 -1
View File
@@ -83,7 +83,7 @@ def render_artifacts_for_tool(artifacts: list[SandboxArtifact]) -> str:
"""
if not artifacts:
return ""
return "No generated artifacts were found in the workspace."
lines = [
"Generated artifacts (now saved — shown to the user as download cards):",
*[
+73 -16
View File
@@ -20,6 +20,8 @@ not a format translation:
Providers are addressed as ``<hub>:<slug>[@version]`` (e.g.
``eduhub:socratic-tutor@1.2.0``; the hub prefix defaults to ``eduhub``).
ClawHub skills can also be publisher-scoped as
``<hub>:<ownerHandle>/<slug>[@version]``.
Two provider shapes ship in v1:
* :class:`ClawHubProvider` — speaks the ClawHub HTTP API directly (search /
@@ -79,6 +81,7 @@ _BUILTIN_HUBS: dict[str, dict[str, str]] = {
_REF_RE = re.compile(
r"^(?:(?P<hub>[a-z0-9][a-z0-9-]{0,31}):)?"
r"(?:(?P<owner>[A-Za-z0-9][A-Za-z0-9._-]{0,63})/)?"
r"(?P<slug>[a-z0-9][a-z0-9._-]{0,127})"
r"(?:@(?P<version>[A-Za-z0-9][A-Za-z0-9._-]{0,63}))?$"
)
@@ -104,6 +107,7 @@ class HubSkillRef:
hub: str
slug: str
owner_handle: str = ""
display_name: str = ""
summary: str = ""
version: str = ""
@@ -158,17 +162,43 @@ class SkillHubProvider(Protocol):
def parse_hub_ref(ref: str) -> tuple[str, str, str | None]:
"""Split ``<hub>:<slug>[@version]`` into its parts; hub defaults."""
"""Split ``<hub>:[<owner>/]<slug>[@version]`` into its parts; hub defaults.
The returned slug remains publisher-scoped when an owner was supplied. Use
:func:`split_owner_slug` at an API boundary that needs the two fields.
"""
match = _REF_RE.match((ref or "").strip())
if match is None:
raise HubError(f"Invalid skill reference `{ref}`. Expected <hub>:<slug>[@version].")
raise HubError(
f"Invalid skill reference `{ref}`. Expected <hub>:[<owner>/]<slug>[@version]."
)
return (
match.group("hub") or default_hub(),
match.group("slug"),
f"{match.group('owner')}/{match.group('slug')}"
if match.group("owner")
else match.group("slug"),
match.group("version"),
)
def split_owner_slug(slug: str) -> tuple[str, str]:
"""Split a publisher-scoped slug into ``(ownerHandle, slug)``."""
owner, separator, skill_slug = (slug or "").strip().partition("/")
if not separator:
return "", owner
return owner, skill_slug
def _owner_handle_from_row(row: dict[str, Any]) -> str:
"""Read ClawHub's publisher handle from its current and nested shapes."""
handle = str(row.get("ownerHandle") or "").strip()
for key in ("owner", "publisher"):
owner = row.get(key)
if isinstance(owner, dict):
handle = handle or str(owner.get("handle") or "").strip()
return handle
# ── safe archive extraction (directory-preserving) ──────────────────────
@@ -310,6 +340,7 @@ class ClawHubProvider:
HubSkillRef(
hub=self.name,
slug=slug,
owner_handle=_owner_handle_from_row(row),
display_name=str(row.get("displayName") or row.get("name") or slug),
summary=str(row.get("summary") or row.get("description") or ""),
version=str(row.get("version") or ""),
@@ -318,9 +349,13 @@ class ClawHubProvider:
return refs
def verify(self, slug: str, *, version: str | None = None) -> HubVerdict:
owner_handle, skill_slug = split_owner_slug(slug)
try:
response = self._get(
f"/skills/{slug}/verify", version=version, tag=None if version else "latest"
f"/skills/{skill_slug}/verify",
version=version,
tag=None if version else "latest",
ownerHandle=owner_handle or None,
)
payload = response.json()
except (HubError, ValueError) as exc:
@@ -333,8 +368,13 @@ class ClawHubProvider:
return HubVerdict(status="suspicious", detail=decision or "hub flagged this package")
def fetch(self, slug: str, *, version: str | None = None) -> FetchedSkill:
owner_handle, skill_slug = split_owner_slug(slug)
response = self._get(
"/download", slug=slug, version=version, tag=None if version else "latest"
"/download",
slug=skill_slug,
version=version,
tag=None if version else "latest",
ownerHandle=owner_handle or None,
)
tmp = Path(tempfile.mkdtemp(prefix="deeptutor-skill-"))
try:
@@ -348,15 +388,21 @@ class ClawHubProvider:
raise
resolved_version = version or self._latest_version(slug)
return FetchedSkill(
ref=HubSkillRef(hub=self.name, slug=slug, version=resolved_version),
ref=HubSkillRef(
hub=self.name,
slug=skill_slug,
owner_handle=owner_handle,
version=resolved_version,
),
root=root,
cleanup_dir=tmp,
)
def _latest_version(self, slug: str) -> str:
"""Resolve the version actually served by an untagged download."""
owner_handle, skill_slug = split_owner_slug(slug)
try:
payload = self._get(f"/skills/{slug}").json()
payload = self._get(f"/skills/{skill_slug}", ownerHandle=owner_handle or None).json()
except (HubError, ValueError):
return ""
if not isinstance(payload, dict):
@@ -376,8 +422,10 @@ class ClawHubProvider:
return None
stats = row.get("stats") if isinstance(row.get("stats"), dict) else {}
owner = row.get("owner") if isinstance(row.get("owner"), dict) else {}
owner_handle = _owner_handle_from_row(row)
return {
"slug": slug,
"owner_handle": owner_handle,
"name": str(row.get("displayName") or row.get("name") or slug),
"summary": str(row.get("summary") or row.get("description") or ""),
"version": str(row.get("version") or ""),
@@ -424,14 +472,19 @@ class ClawHubProvider:
def detail(self, slug: str) -> dict[str, Any]:
"""Full metadata + SKILL.md body for one hub skill (browser detail view)."""
owner_handle, skill_slug = split_owner_slug(slug)
try:
payload = self._get(f"/skills/{slug}").json()
payload = self._get(f"/skills/{skill_slug}", ownerHandle=owner_handle or None).json()
except ValueError as exc:
raise HubError(f"{self.name}: skill detail returned invalid JSON") from exc
if not isinstance(payload, dict):
raise HubError(f"{self.name}: unrecognised skill detail shape")
skill = payload.get("skill") if isinstance(payload.get("skill"), dict) else payload
listing = self._listing_from_row(skill) or {"slug": slug, "name": slug}
listing = self._listing_from_row(skill) or {
"slug": skill_slug,
"name": skill_slug,
}
listing.setdefault("owner_handle", owner_handle)
# Owner sometimes lives at the envelope top level, not inside ``skill``.
if not listing.get("owner") and isinstance(payload.get("owner"), dict):
owner = payload["owner"]
@@ -687,6 +740,7 @@ def install_from_hub(
"""
hub, slug, version = parse_hub_ref(ref)
resolved = provider or get_hub_provider(hub)
owner_handle, skill_slug = split_owner_slug(slug)
verdict = resolved.verify(slug, version=version)
if verdict.status == "suspicious" and not allow_unverified:
@@ -697,6 +751,15 @@ def install_from_hub(
)
fetched = resolved.fetch(slug, version=version)
origin = {
"hub": hub,
"slug": skill_slug,
"version": fetched.ref.version or version or "",
"verdict": verdict.status,
"installed_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
}
if owner_handle:
origin["owner_handle"] = owner_handle
try:
result = service.install_tree(
fetched.root,
@@ -706,13 +769,7 @@ def install_from_hub(
# Stamp the source hub as a tag so imported skills are visibly
# grouped (e.g. an ``eduhub`` tag) in the user's Skills list.
extra_tags=[hub],
origin={
"hub": hub,
"slug": slug,
"version": fetched.ref.version or version or "",
"verdict": verdict.status,
"installed_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
},
origin=origin,
)
finally:
fetched.cleanup()
+1 -1
View File
@@ -20,7 +20,7 @@ A `.docx` is a ZIP of XML parts. Body text lives in `word/document.xml`. Two tie
- **Advanced — raw OOXML via `zipfile`**: only for what python-docx cannot express — tracked changes (redlines), comments, and exact-fidelity edits that must preserve every untouched byte. See [Raw OOXML](#raw-ooxml-advanced).
Work in the current directory (uploaded files land here). Write output to a new filename; don't overwrite the source.
After `exec` completes, use the Generated artifacts URL from the tool result in the final answer so the user can download the document.
Run Python through `code_execution`, save output in the current directory, and refer to the document exactly as the Generated artifacts list names it. Use `exec` only for a genuinely shell-only command; never put this source in `python -c` or a heredoc.
## Read / extract
+2 -2
View File
@@ -19,8 +19,8 @@ Work PDFs in the sandbox with preinstalled Python libs. Pick the library by task
- **Fill forms** → `pypdf` (fillable AcroForm fields) or annotation overlay (flat forms).
- **Create from scratch** → `reportlab`.
Write a short Python snippet and run it via `exec`. Save outputs to the workspace dir.
After `exec` completes, use the Generated artifacts URL from the tool result in the final answer so the user can download the PDF.
Write complete Python source and run it via `code_execution`. Save outputs to the workspace dir.
After execution, refer to the PDF exactly as the Generated artifacts list names it. Use `exec` only for a genuinely shell-only command; never put this source in `python -c` or a heredoc.
## Extract text and tables (pdfplumber)
+4 -4
View File
@@ -17,10 +17,10 @@ Work with PowerPoint `.pptx` files using **python-pptx** (preinstalled). A `.ppt
is a ZIP of XML parts; python-pptx handles the structure so you rarely touch XML.
Drop to raw OOXML only for the few things the library can't express (see Advanced).
All work happens in the sandbox `exec` shell, in the current workspace dir where
uploaded files land. Write a short Python heredoc or temp `.py` and run it.
After `exec` completes, use the Generated artifacts URL from the tool result in
the final answer so the user can download the deck.
Run complete Python source with `code_execution` in the current workspace dir
where uploaded files land. Refer to the deck exactly as the Generated artifacts
list names it. Use `exec` only for a genuinely shell-only command; never put
this source in `python -c` or a heredoc.
## Mental model
- A presentation has **slides**; each slide is built from a **layout**; layouts
+5 -4
View File
@@ -14,10 +14,11 @@ requires:
# Excel (.xlsx) workbooks
Work in the workspace dir (where uploads land) by writing short Python run via
`exec`. Two libraries, both preinstalled — pick by task:
After `exec` completes, use the Generated artifacts URL from the tool result in
the final answer so the user can download the workbook.
Work in the workspace dir (where uploads land) by running complete Python
source via `code_execution`. Two libraries, both preinstalled — pick by task:
Refer to the workbook exactly as the Generated artifacts list names it. Use
`exec` only for a genuinely shell-only command; never put this source in
`python -c` or a heredoc.
- **pandas** — bulk tabular read/write/analysis. Use for "load this sheet,
compute, dump a table". Drops all formatting and formulas.
+6 -2
View File
@@ -23,6 +23,8 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from deeptutor.utils.text_display import decode_escaped_unicode_for_display
MAX_QUESTIONS = 4
MAX_OPTIONS = 8
MAX_OPTION_CHARS = 120 # option label
@@ -253,8 +255,10 @@ def _coerce_string(value: Any) -> str:
if value is None:
return ""
if isinstance(value, str):
return value
return str(value)
raw = value
else:
raw = str(value)
return decode_escaped_unicode_for_display(raw)
__all__ = [
+5 -4
View File
@@ -340,10 +340,11 @@ class CodeExecutionTool(_PromptHintsMixin, BaseTool):
name="code_execution",
description=(
"Run a code snippet in an isolated sandbox and return its "
"stdout/stderr. Pass complete, ready-to-run source in `code` "
"and pick `language` (python, c, or cpp). Use for calculation, "
"algorithm checking, and numerical verification — print results "
"to stdout. Not a substitute for explaining your reasoning."
"stdout/stderr plus any files generated in the workspace. Pass "
"complete, ready-to-run source in `code` and pick `language` "
"(python, c, or cpp). Use it for calculation, data processing, "
"and code-generated deliverables instead of embedding source in "
"an exec command. Print concise results to stdout."
),
parameters=[
ToolParameter(
+2
View File
@@ -15,6 +15,7 @@ from deeptutor.capabilities.mastery.tools import (
MasteryLeaveTool,
MasteryPathsTool,
MasteryQuizTool,
MasterySkipQuestionTool,
MasteryStatusTool,
MasterySwitchTool,
)
@@ -28,6 +29,7 @@ __all__ = [
"MasteryLeaveTool",
"MasteryPathsTool",
"MasteryQuizTool",
"MasterySkipQuestionTool",
"MasteryStatusTool",
"MasterySwitchTool",
]
@@ -1,12 +1,12 @@
short_description: "Run a code snippet (python/c/cpp) in an isolated sandbox; returns stdout/stderr."
when_to_use: "Use when computation, algorithm checking, or numerical verification is more reliable than mental calculation."
short_description: "Run a code snippet (python/c/cpp) in an isolated sandbox; returns stdout/stderr and generated files."
when_to_use: "Use for computation, verification, data processing, or creating a file with Python instead of embedding source in a shell command."
input_format: "`language` (python, c, or cpp) + `code` — the complete, ready-to-run source. Optional `stdin` and `timeout` (seconds, default 30)."
guideline: "Write complete source yourself and print results to stdout. Use code execution for objective verification, not as a substitute for explaining reasoning."
guideline: "Write complete source yourself, save output files to the working directory, and print a concise completion message. Never run this source through exec with `python -c` or a heredoc; use exec only for a command that is genuinely shell-only."
note: "Runs in this turn's workspace under the same OS-isolated sandbox as `exec`; unavailable when no sandbox backend is configured. Save generated files to the working directory to surface them as artifacts."
phase: "verification"
aliases:
- name: run_code
description: "Run a code snippet (python/c/cpp) for calculation, verification, or visualization."
description: "Run a code snippet (python/c/cpp) for calculation, verification, visualization, or file generation."
input_format: "`language` + `code`; optional `stdin`, `timeout`."
when_to_use: "Use for objective checks, quick calculations, or small experiments."
when_to_use: "Use for objective checks, quick calculations, small experiments, or Python-generated files."
phase: "verification"
+1 -1
View File
@@ -1,6 +1,6 @@
short_description: "Run a shell command inside an isolated sandbox; returns stdout/stderr + exit code."
when_to_use: "For data processing, running a skill's bundled scripts, or invoking CLI tools the task needs. Not for destructive or system-management commands."
input_format: "`command` — the shell command. Optional `timeout` — seconds (default 30, max 300). Runs in this turn's workspace directory."
guideline: "Prefer non-interactive flags (e.g. `-y`). Keep output small; pipe through `head`/`grep` when a command is chatty. Read a skill's SKILL.md before running its scripts. If the user asks you to create/export a file, run the command, save the file in the workspace, then include any Generated artifacts URL from the tool result in your final answer."
guideline: "Prefer non-interactive flags (e.g. `-y`). Keep output small; pipe through `head`/`grep` when a command is chatty. Read a skill's SKILL.md before running its scripts. For Python work or file generation, pass complete source to code_execution instead of `python -c` or a heredoc; use exec only for genuinely shell-only commands. Refer to generated artifacts exactly as the tool result lists them."
note: "Destructive patterns (rm -rf, mkfs, shutdown, …) are blocked. The sandbox confines filesystem and network access; commands that need the open internet may fail."
phase: "expansion"
@@ -1,12 +1,12 @@
short_description: "在隔离沙箱中运行一段代码(python/c/cpp),返回 stdout/stderr。"
when_to_use: "当计算、算法校验或数值验证比纯手算更可靠时使用。"
short_description: "在隔离沙箱中运行一段代码(python/c/cpp),返回 stdout/stderr 和生成文件。"
when_to_use: "用于计算、校验、数据处理,或用 Python 生成文件,而不是把源码嵌进 shell 命令。"
input_format: "`language`(python、c 或 cpp)+ `code`——完整、可直接运行的源码。可选 `stdin` 与 `timeout`(秒,默认 30)。"
guideline: "自行写出完整源码并把结果打印到 stdout;代码执行适合做客观验证,不应替代文字解释。"
guideline: "自行写出完整源码,把输出文件保存到当前工作目录,并打印简短完成信息。绝不要通过 exec 的 `python -c` 或 heredoc 运行这段源码;exec 只用于真正必须使用 shell 的命令。"
note: "在本回合 workspace 内运行,与 `exec` 共用同一套 OS 级隔离沙箱;未配置沙箱后端时不可用。把生成文件保存到工作目录即可作为产物输出。"
phase: "verification"
aliases:
- name: run_code
description: "运行一段代码(python/c/cpp),用于计算、验证或可视化。"
description: "运行一段代码(python/c/cpp),用于计算、验证、可视化或生成文件。"
input_format: "`language` + `code`;可选 `stdin`、`timeout`。"
when_to_use: "适合做客观校验、快速计算或小规模实验。"
when_to_use: "适合做客观校验、快速计算、小规模实验或用 Python 生成文件。"
phase: "verification"
+1 -1
View File
@@ -1,6 +1,6 @@
short_description: "在隔离沙箱中执行 shell 命令,返回 stdout/stderr 与退出码。"
when_to_use: "用于数据处理、运行技能自带脚本、调用任务所需的 CLI 工具。不要用于破坏性或系统管理类命令。"
input_format: "`command` — shell 命令。可选 `timeout` — 秒(默认 30,上限 300)。命令运行在本回合的工作目录中。"
guideline: "优先使用非交互参数(如 `-y`)。控制输出体量,命令过于啰嗦时用 `head`/`grep` 过滤。运行技能脚本前先读其 SKILL.md。若用户要求创建/导出文件,执行命令并把文件保存到工作目录,然后在最终回答中给出工具结果里的 Generated artifacts 下载链接。"
guideline: "优先使用非交互参数(如 `-y`)。控制输出体量,命令过于啰嗦时用 `head`/`grep` 过滤。运行技能脚本前先读其 SKILL.md。Python 工作或文件生成应把完整源码传给 code_execution,不要用 `python -c` 或 heredoc;exec 只用于真正必须使用 shell 的命令。最终回答按工具结果原样引用生成文件。"
note: "破坏性命令(rm -rf、mkfs、shutdown 等)会被拦截。沙箱限制文件与网络访问,需要公网的命令可能失败。"
phase: "expansion"
+31
View File
@@ -0,0 +1,31 @@
"""Helpers for learner-facing text that models sometimes double-encode."""
from __future__ import annotations
import codecs
import re
# Match dense JSON-style ``\\uXXXX`` runs (3+ escapes), mirroring the web
# markdown decoder so mastery / ask_user cards do not leak literal escapes (#973).
_ESCAPED_UNICODE_RUN = re.compile(r"(?:\\u[0-9a-fA-F]{4}){3,}")
def decode_escaped_unicode_for_display(text: str) -> str:
"""Decode dense ``\\uXXXX`` runs when they clearly represent non-ASCII text."""
if not text or "\\u" not in text:
return text
def _replace(match: re.Match[str]) -> str:
run = match.group(0)
try:
decoded = codecs.decode(run, "unicode_escape")
except (UnicodeDecodeError, ValueError):
return run
if any(ord(ch) > 0x7F for ch in decoded):
return decoded
return run
return _ESCAPED_UNICODE_RUN.sub(_replace, text)
__all__ = ["decode_escaped_unicode_for_display"]
+20 -4
View File
@@ -93,21 +93,37 @@ def register(app: typer.Typer) -> None:
console.print("[dim]No skills matched.[/]")
return
table = Table(title=f"{target}: {query}")
table.add_column("Ref", style="bold")
table.add_column("Ref", style="bold", overflow="fold")
table.add_column("Publisher")
table.add_column("Version")
table.add_column("Summary")
for ref in refs:
install_ref = (
f"{ref.hub}:{ref.owner_handle}/{ref.slug}"
if ref.owner_handle
else f"{ref.hub}:{ref.slug}"
)
table.add_row(
f"{ref.hub}:{ref.slug}",
install_ref,
ref.owner_handle or "-",
ref.version or "-",
ref.summary[:100] or ref.display_name,
)
console.print(table)
console.print("[dim]Install with: deeptutor skill install <ref>[/]")
install_refs = [
f"{ref.hub}:{ref.owner_handle}/{ref.slug}"
if ref.owner_handle
else f"{ref.hub}:{ref.slug}"
for ref in refs
]
console.print("[dim]Install with:[/] " + ", ".join(install_refs))
@app.command("install")
def skill_install(
ref: str = typer.Argument(..., help="Skill ref: <hub>:<slug>[@version]."),
ref: str = typer.Argument(
...,
help="Skill ref: <hub>:[<owner>/]<slug>[@version].",
),
name: str | None = typer.Option(
None, "--name", help="Install under a different local skill name."
),
+1 -1
View File
@@ -55,7 +55,7 @@ dependencies = [
"openpyxl>=3.1.0",
"python-pptx>=1.0.0",
"pypdf>=4.0.0",
"pdfplumber>=0.11.0,<0.11.8",
"pdfplumber>=0.11.0",
"reportlab>=4.0.0",
"defusedxml>=0.7.1",
"youtube-transcript-api>=1.2.0,<2.0.0",
+9 -17
View File
@@ -12,8 +12,8 @@ description = "An agent-native intelligent learning companion with multi-agent c
# Capped below 3.14 on purpose (issue #664): on 3.14 pip can't find wheels for
# some compiled base deps (e.g. faiss-cpu) and silently backtracks into a
# doomed source build that dies with "subprocess-exited-with-error". The heavy
# RAG extras (graphrag, rag-lightrag) already carry a `python_version < '3.14'`
# marker for the same reason; capping here makes pip refuse 3.14 with a
# GraphRAG also carries a `python_version < '3.14'` marker; capping the project
# itself makes every install, including LightRAG, refuse 3.14 with a
# readable "Requires a different Python" message instead of a build failure.
requires-python = ">=3.11,<3.14"
readme = "README.md"
@@ -61,7 +61,7 @@ dependencies = [
"openpyxl>=3.1.0",
"python-pptx>=1.0.0",
"pypdf>=4.0.0",
"pdfplumber>=0.11.0,<0.11.8", # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)
"pdfplumber>=0.11.0",
"reportlab>=4.0.0",
"defusedxml>=0.7.1",
"youtube-transcript-api>=1.2.0,<2.0.0",
@@ -110,7 +110,7 @@ cli = [
"openpyxl>=3.1.0",
"python-pptx>=1.0.0",
"pypdf>=4.0.0",
"pdfplumber>=0.11.0,<0.11.8", # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)
"pdfplumber>=0.11.0",
"reportlab>=4.0.0",
"defusedxml>=0.7.1",
"youtube-transcript-api>=1.2.0,<2.0.0",
@@ -230,19 +230,11 @@ math-animator = ["manim>=0.19.0"]
# (1.4.5) and silently downgrades. Floor is 3.0.1 (3.0.0/3.0.3 were yanked).
graphrag = ["graphrag>=3.0.1,<4.0.0; python_version < '3.14'"]
# LightRAG knowledge-base engine (HKUDS/LightRAG) with multimodal parsing via
# RAG-Anything (HKUDS/RAG-Anything). Optional, heavy (pulls MinerU transitively —
# see the pdfplumber pin above). The pipeline imports lazily and the adapter is
# isolated in services/rag/pipelines/lightrag/engine.py. raganything pulls
# `mineru[core]`, which is capped at python <3.14, so this carries the same
# `python_version` marker as graphrag to avoid a silent backtrack/downgrade on
# 3.14+. Floor is 1.0.1 (no 1.0.0 was ever published) with a <2.0.0 ceiling so
# a future API-breaking 2.x isn't pulled in silently.
# 1.2.5 is the first release carrying the ``lightrag_kwargs`` passthrough the
# LightRAG concurrency/extraction settings ride on. Older installs still run —
# engine.py drops knobs the installed version cannot take — but a fresh install
# should get the capable one.
rag-lightrag = ["raganything>=1.2.5,<2.0.0; python_version < '3.14'"]
# Built-in LightRAG provider. The exact release is intentional: the adapter
# isolates a private rc2 source-resolver seam and locks it with smoke tests.
# MinerU remains an independently selected DeepTutor parser and is not a
# transitive dependency of this extra.
rag-lightrag = ["lightrag-hku==1.5.7rc2"]
# Dev/test tooling. Mirrors requirements/dev.txt.
dev = [
+1 -1
View File
@@ -52,7 +52,7 @@ python-docx>=1.1.0
openpyxl>=3.1.0
python-pptx>=1.0.0
pypdf>=4.0.0
pdfplumber>=0.11.0,<0.11.8 # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)
pdfplumber>=0.11.0
reportlab>=4.0.0
defusedxml>=0.7.1
youtube-transcript-api>=1.2.0,<2.0.0
+66
View File
@@ -0,0 +1,66 @@
"""Language fields must survive both book creation transports."""
from __future__ import annotations
from fastapi import FastAPI
from starlette.testclient import TestClient
from deeptutor.api.routers import book as book_router
from deeptutor.book.models import Book, BookProposal
class _RecordingEngine:
def __init__(self) -> None:
self.kwargs: dict | None = None
async def create_book(self, **kwargs):
self.kwargs = kwargs
return Book(id="bk_language", title="Language Test"), BookProposal(title="Language Test")
def _install(monkeypatch, engine: _RecordingEngine) -> FastAPI:
monkeypatch.setattr(book_router, "get_book_engine", lambda: engine)
monkeypatch.setattr(book_router, "can_create_book", lambda: True)
app = FastAPI()
app.include_router(book_router.router, prefix="/api/v1/book")
return app
def test_rest_create_passes_requested_and_fallback_language(monkeypatch) -> None:
engine = _RecordingEngine()
app = _install(monkeypatch, engine)
response = TestClient(app).post(
"/api/v1/book/books",
json={
"user_intent": "Create a book",
"language": "auto",
"fallback_language": "zh",
},
)
assert response.status_code == 200
assert engine.kwargs is not None
assert engine.kwargs["language"] == "auto"
assert engine.kwargs["fallback_language"] == "zh"
def test_websocket_create_passes_fallback_language(monkeypatch) -> None:
engine = _RecordingEngine()
app = _install(monkeypatch, engine)
with TestClient(app).websocket_connect("/api/v1/book/ws") as ws:
ws.send_json(
{
"type": "create",
"user_intent": "Create a book",
"language": "auto",
"fallback_language": "zh",
}
)
result = ws.receive_json()
assert result["type"] == "create_result"
assert engine.kwargs is not None
assert engine.kwargs["language"] == "auto"
assert engine.kwargs["fallback_language"] == "zh"
+24
View File
@@ -122,6 +122,30 @@ def test_auth_disabled_reads_local_admin_output(output_app) -> None:
assert response.content == b"local output"
def test_authenticated_user_downloads_visible_partner_output(output_app, monkeypatch) -> None:
relative_path = "workspace/chat/chat/session-1/code_runs/chart.png"
alice = TokenPayload(username="alice", role="user", user_id="u_alice")
client, admin_root, _users_root = output_app({"alice-token": alice})
from deeptutor.api.routers import outputs
partner_root = admin_root / "partners" / "math-bot" / "workspace"
_write_output(partner_root, relative_path, b"\x89PNG\r\n\x1a\npartner image")
monkeypatch.setattr(
outputs,
"visible_partners",
lambda: [{"partner_id": "math-bot", "can_manage": True}],
)
with client:
client.cookies.set("dt_token", "alice-token")
response = client.get(f"/api/outputs/{relative_path}")
assert response.status_code == 200
assert response.content.startswith(b"\x89PNG\r\n\x1a\n")
assert response.headers["content-type"] == "image/png"
def test_private_suffix_is_rejected(output_app) -> None:
relative_path = "workspace/chat/chat/session-1/code_runs/private.json"
alice = TokenPayload(username="alice", role="user", user_id="u_alice")
+48
View File
@@ -0,0 +1,48 @@
"""Book creation must persist one concrete language for every later stage."""
from __future__ import annotations
import pytest
from deeptutor.book.engine import BookEngine
from deeptutor.book.models import BookInputs, BookProposal
class _RecordingStorage:
def __init__(self) -> None:
self.books: list = []
self.inputs: list[BookInputs] = []
def save_book(self, book) -> None:
self.books.append(book)
def save_inputs(self, book_id: str, inputs: BookInputs) -> None:
self.inputs.append(inputs)
def save_progress(self, progress) -> None:
self.progress = progress
def append_log(self, *args, **kwargs) -> None:
self.log_calls = (args, kwargs)
@pytest.mark.asyncio
async def test_create_book_resolves_auto_before_inputs_are_persisted(
monkeypatch: pytest.MonkeyPatch,
) -> None:
engine = object.__new__(BookEngine)
engine.storage = _RecordingStorage()
async def fake_ideation(self, ctx, language: str) -> BookProposal:
return BookProposal(title="Language Test", estimated_chapters=1)
monkeypatch.setattr(BookEngine, "_run_ideation", fake_ideation)
book, _proposal = await engine.create_book(
user_intent="Please make a Fourier book in Japanese",
language="auto",
fallback_language="zh",
)
assert book.language == "ja"
assert engine.storage.inputs[0].language == "ja"
+64
View File
@@ -0,0 +1,64 @@
"""Language resolution for automatic book creation."""
from __future__ import annotations
import pytest
from deeptutor.book.language import resolve_book_language
@pytest.mark.parametrize(
("intent", "expected"),
[
("Please create a Fourier book in Japanese", "ja"),
("Write about Japanese history in Spanish", "es"),
("请用日语整理机器学习入门内容", "ja"),
("日本語で書いてください", "ja"),
("한국어로 정리해 주세요", "ko"),
("Сделай книгу по алгоритмам", "ru"),
("帮我整理机器学习入门内容", "zh"),
("Please create a book about Japanese history", "en"),
],
)
def test_auto_uses_high_confidence_language_signals(intent: str, expected: str) -> None:
assert (
resolve_book_language(
user_intent=intent,
requested_language="auto",
fallback_language="en",
)
== expected
)
def test_auto_falls_back_to_the_interface_language() -> None:
assert (
resolve_book_language(
user_intent="Create a book about distributed systems",
requested_language="auto",
fallback_language="zh",
)
== "zh"
)
def test_explicit_language_selection_wins_over_intent_signals() -> None:
assert (
resolve_book_language(
user_intent="请用日语整理内容",
requested_language="zh",
fallback_language="en",
)
== "zh"
)
def test_traditional_chinese_requests_resolve_to_the_regional_code() -> None:
assert (
resolve_book_language(
user_intent="請用繁體中文寫一本演算法書",
requested_language="auto",
fallback_language="en",
)
== "zh-tw"
)
+49
View File
@@ -0,0 +1,49 @@
"""CLI tests for skill hub commands."""
from __future__ import annotations
import io
from rich.console import Console
from typer.testing import CliRunner
from deeptutor.services.skill.hub import HubSkillRef
from deeptutor_cli.main import app
runner = CliRunner()
class FakeProvider:
def search(self, query: str, *, limit: int = 10) -> list[HubSkillRef]:
assert query == "stock analysis"
return [
HubSkillRef(
hub="clawhub",
slug="stock-analysis",
owner_handle="acme",
display_name="Stock Analysis",
summary="Analyze stock filings",
version="1.2.0",
)
]
def test_skill_search_shows_publisher_scoped_install_refs(monkeypatch) -> None:
import deeptutor.services.skill.hub as hub
import deeptutor_cli.skill as skill_cli
output = io.StringIO()
monkeypatch.setattr(hub, "get_hub_provider", lambda _hub: FakeProvider())
monkeypatch.setattr(
skill_cli,
"console",
Console(file=output, width=120, force_terminal=False),
)
result = runner.invoke(app, ["skill", "search", "stock analysis"])
assert result.exit_code == 0, result.output
rendered = output.getvalue()
assert "Publisher" in rendered
assert "acme" in rendered
assert "clawhub:acme/stock-analysis" in rendered
+15
View File
@@ -37,3 +37,18 @@ def test_assistant_message_with_tool_calls_preserves_order_and_arguments() -> No
"name": "read",
"arguments": '{"id":2}',
}
def test_assistant_message_with_tool_calls_replays_reasoning_content() -> None:
message = assistant_message_with_tool_calls(
content="",
tool_calls=[{"id": "call-1", "name": "search"}],
reasoning_content="Need to look this up.",
)
assert message["reasoning_content"] == "Need to look this up."
assert "reasoning_content" not in assistant_message_with_tool_calls(
content="hi",
tool_calls=[{"id": "call-1", "name": "search"}],
reasoning_content="",
)
+59
View File
@@ -104,6 +104,35 @@ async def test_exec_tool_reports_generated_public_artifacts(
assert result.sources[0]["url"].endswith("/report.pdf")
@pytest.mark.asyncio
async def test_exec_tool_reports_missing_artifacts_after_success(
tmp_path, monkeypatch: pytest.MonkeyPatch
) -> None:
path_service = PathService(workspace_root=tmp_path / "data")
workdir = path_service.get_task_workspace("chat", "turn_1") / "exec"
workdir.mkdir(parents=True, exist_ok=True)
class FakeSandboxService:
async def run(self, request, *, user_id: str):
return ExecResult(stdout="done\n", exit_code=0)
import deeptutor.services.sandbox as sandbox_pkg
import deeptutor.services.sandbox.artifacts as sandbox_artifacts
monkeypatch.setattr(sandbox_pkg, "get_sandbox_service", lambda: FakeSandboxService())
monkeypatch.setattr(sandbox_artifacts, "get_path_service", lambda: path_service)
result = await ExecTool().execute(
command="python build_pdf.py",
_sandbox_user_id="user-1",
_sandbox_workdir=str(workdir),
)
assert result.success is True
assert "No generated artifacts were found in the workspace." in result.content
assert result.metadata["artifacts"] == []
@pytest.mark.asyncio
async def test_brainstorm_tool_passes_llm_arguments(monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, Any] = {}
@@ -269,6 +298,36 @@ async def test_code_execution_tool_runs_python_via_sandbox(
assert "main.py" not in artifact_names
@pytest.mark.asyncio
async def test_code_execution_tool_warns_when_no_artifacts_are_generated(
tmp_path, monkeypatch: pytest.MonkeyPatch
) -> None:
path_service = PathService(workspace_root=tmp_path / "data")
workdir = path_service.get_task_workspace("chat", "turn_1") / "code_runs"
class FakeSandboxService:
async def run(self, request, *, user_id: str):
return ExecResult(stdout="PDF created\n", exit_code=0)
import deeptutor.services.sandbox as sandbox_pkg
import deeptutor.services.sandbox.artifacts as sandbox_artifacts
monkeypatch.setattr(sandbox_pkg, "get_sandbox_service", lambda: FakeSandboxService())
monkeypatch.setattr(sandbox_artifacts, "get_path_service", lambda: path_service)
result = await CodeExecutionTool().execute(
language="python",
code="print('PDF created')",
_sandbox_user_id="user-1",
_sandbox_workdir=str(workdir),
)
assert result.success is True
assert "No generated artifacts were found in the workspace." in result.content
assert result.metadata["artifacts"] == []
assert result.sources == []
@pytest.mark.asyncio
async def test_code_execution_tool_compiles_cpp(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
from pathlib import Path
+33
View File
@@ -464,3 +464,36 @@ async def test_visualize_capability_passes_attachments_to_analysis_agent(
assert captured["analysis"]["attachments"][0].filename == "figure.png"
result_event = next(event for event in events if event.type == StreamEventType.RESULT)
assert result_event.metadata["render_type"] == "svg"
@pytest.mark.asyncio
async def test_deep_question_rejects_empty_custom_topic_before_workspace(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Invalid input returns a clear error before workspace allocation."""
monkeypatch.setattr(
"deeptutor.services.llm.config.get_llm_config",
lambda: SimpleNamespace(api_key="", base_url="", api_version=""),
)
class FailingPathService:
def get_task_workspace(self, *_args: Any, **_kwargs: Any) -> str:
raise AssertionError("workspace must not be allocated for invalid input")
monkeypatch.setattr(
"deeptutor.services.path_service.get_path_service",
lambda: FailingPathService(),
)
context = UnifiedContext(
user_message="",
config_overrides={"mode": "custom", "topic": ""},
language="en",
)
events = await _collect_events(lambda bus: DeepQuestionCapability().run(context, bus))
errors = [event for event in events if event.type == StreamEventType.ERROR]
assert errors
assert "topic" in errors[-1].content.lower()
assert errors[-1].metadata["code"] == "topic_required"
+45
View File
@@ -0,0 +1,45 @@
# LightRAG parser-bridge fixtures
`original.pdf` is generated by `generate_original_pdf.py` and is original
DeepTutor test material licensed under the repository's Apache-2.0 license. It
contains only synthetic text, an equation, a small table, and a drawn rectangle;
it has no third-party document content.
Generated file SHA-256: `e2abd3404f3a03d90c36feec19786689892434e730841cbdbd2a1a28875f3a80`.
Golden parser outputs in this directory must record the exact source commit or
authenticated MinerU API capture date, response schema/version, capture command,
and SHA-256. Secrets and transient service metadata must never be committed.
The current MinerU v4 capture is produced interactively with:
```bash
.venv/bin/python tests/fixtures/lightrag_bridge/capture_current_mineru.py
```
The script prompts privately with `getpass`; it does not accept the token in a
command argument, environment variable, output file, or log.
`mineru-legacy-official-example/content_list.json` is extracted byte-for-byte
from the official MinerU documentation at commit
`61cc6886fe3edda8aa1c5b8bd2b6eaedddb8af99` by
`extract_legacy_example.py`. Its provenance explicitly identifies it as an
official schema example, not a live parser run. The authenticated current
capture remains the real-output fixture for `original.pdf`.
## Frozen mapping contract
| MinerU field | LightRAG public Sidecar field | Failure boundary |
| --- | --- | --- |
| `title`, `section_header`, or positive `text_level` | `IRBlock.heading`, `level`, `parent_headings` | Empty headings remain ordinary content and cannot create a hierarchy node. |
| `text`, `content`, `body`, `code_body` | `IRBlock.content_template` | An unknown block with none of these non-empty fields fails the document. |
| `rows` or `table_body` | `IRTable.rows` or `html` | A table with neither a row matrix nor HTML fails before analysis. |
| `table_caption`, `header`, `table_footnote` | `caption`, `table_header`, `footnotes` | Malformed optional values normalize to empty fields; table body remains mandatory. |
| `img_path` or `path` | verified `AssetSpec` plus `IRDrawing.asset_ref` | Absolute/traversal/missing/ambiguous/unfrozen assets fail the document. |
| `image_caption`/`chart_caption`, image/chart footnote, format | `IRDrawing.caption`, `footnotes`, `fmt` | No prompt-only or missing-asset fallback is allowed. |
| equation text/body plus `text_format` | `IREquation.latex`, `is_block` | Empty equation content fails the document. |
| `page_idx` or `page`, and `bbox` | `IRPosition.anchor`, `range` | Integer `page_idx` is converted from zero-based to one-based; invalid bbox is omitted. |
Both raw parser fixtures and expected Sidecar assertions are immutable test
inputs. Production code may import only LightRAG's public Sidecar IR and writer;
the upstream MinerU builder is comparison evidence, not a runtime dependency.
@@ -0,0 +1,74 @@
"""Capture a current authenticated MinerU v4 result without storing its token."""
from __future__ import annotations
from datetime import datetime, timezone
import getpass
import hashlib
import json
from pathlib import Path
import shutil
import tempfile
from deeptutor.services.parsing.engines.mineru.cloud import parse_cloud
from deeptutor.services.parsing.engines.mineru.config import MinerUConfig
HERE = Path(__file__).resolve().parent
SOURCE = HERE / "original.pdf"
TARGET = HERE / "mineru-v2-current"
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def main() -> None:
if TARGET.exists():
raise SystemExit(f"Refusing to overwrite existing capture: {TARGET}")
token = getpass.getpass("MinerU API token (not stored): ").strip()
if not token:
raise SystemExit("No token entered")
config = MinerUConfig(
mode="cloud",
api_token=token,
model_version="pipeline",
enable_formula=True,
enable_table=True,
)
try:
with tempfile.TemporaryDirectory(prefix="deeptutor-mineru-capture-") as raw:
parsed = parse_cloud(SOURCE, Path(raw), config)
candidates = sorted(parsed.rglob("*_content_list.json"))
if len(candidates) != 1:
raise RuntimeError(f"Expected one content_list artifact, found {len(candidates)}")
content_root = candidates[0].parent
shutil.copytree(content_root, TARGET)
finally:
token = ""
files = {
path.relative_to(TARGET).as_posix(): _sha256(path)
for path in sorted(TARGET.rglob("*"))
if path.is_file()
}
provenance = {
"capture_schema": 1,
"captured_at_utc": datetime.now(timezone.utc).isoformat(),
"service": "https://mineru.net/api/v4",
"model_version": "pipeline",
"authenticated": True,
"source": {"path": "../original.pdf", "sha256": _sha256(SOURCE)},
"artifacts": files,
}
(TARGET / "deeptutor-fixture-provenance.json").write_text(
json.dumps(provenance, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
print(f"Captured {len(files)} artifact(s) in {TARGET}")
if __name__ == "__main__":
main()
@@ -0,0 +1,47 @@
"""Extract MinerU's official legacy content-list example byte-for-byte."""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
import subprocess
COMMIT = "61cc6886fe3edda8aa1c5b8bd2b6eaedddb8af99"
SOURCE_PATH = "docs/en/reference/output_files.md"
DEFAULT_REPOSITORY = Path("/home/ubuntu/sources/github.com/opendatalab/MinerU")
HERE = Path(__file__).resolve().parent
TARGET = HERE / "mineru-legacy-official-example"
def main(repository: Path = DEFAULT_REPOSITORY) -> None:
if TARGET.exists():
raise SystemExit(f"Refusing to overwrite existing fixture: {TARGET}")
markdown = subprocess.check_output(
["git", "-C", str(repository), "show", f"{COMMIT}:{SOURCE_PATH}"], text=True
)
heading = "#### Content List (content_list.json)"
section = markdown.split(heading, 1)[1]
sample = section.split("##### Sample Data", 1)[1]
payload = sample.split("```json", 1)[1].split("```", 1)[0].strip().encode("utf-8") + b"\n"
json.loads(payload)
TARGET.mkdir()
output = TARGET / "content_list.json"
output.write_bytes(payload)
provenance = {
"fixture_schema": 1,
"kind": "official-legacy-schema-example",
"repository": "https://github.com/opendatalab/MinerU.git",
"commit": COMMIT,
"source_path": SOURCE_PATH,
"source_section": heading,
"content_sha256": hashlib.sha256(payload).hexdigest(),
"note": "Exact official documentation example; not a live parser capture.",
}
(TARGET / "deeptutor-fixture-provenance.json").write_text(
json.dumps(provenance, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
if __name__ == "__main__":
main()
+56
View File
@@ -0,0 +1,56 @@
"""Generate the redistributable MinerU bridge fixture PDF."""
from io import BytesIO
from pathlib import Path
from PIL import Image, ImageDraw
from reportlab.lib.pagesizes import letter
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen import canvas
TARGET = Path(__file__).with_name("original.pdf")
def main() -> None:
page = canvas.Canvas(str(TARGET), pagesize=letter, invariant=True)
page.setTitle("DeepTutor LightRAG Bridge Fixture")
page.setAuthor("DeepTutor contributors")
page.setFont("Helvetica-Bold", 18)
page.drawString(72, 720, "DeepTutor LightRAG Bridge Fixture")
page.setFont("Helvetica", 11)
page.drawString(72, 690, "A short paragraph preserves text and heading hierarchy.")
page.setFont("Times-Italic", 18)
page.drawCentredString(306, 650, "E = m c^2")
page.setFont("Helvetica-Bold", 11)
page.drawString(72, 610, "Table 1. Retrieval engine paths")
columns = (72, 222, 372)
rows = (590, 566, 542)
for x in columns:
page.line(x, rows[-1], x, rows[0])
for y in rows:
page.line(columns[0], y, columns[-1], y)
page.setFont("Helvetica", 10)
page.drawString(82, 574, "Engine")
page.drawString(232, 574, "Path")
page.drawString(82, 550, "LightRAG")
page.drawString(232, 550, "Native")
image = Image.new("RGB", (360, 160), "white")
draw = ImageDraw.Draw(image)
draw.line((35, 130, 330, 130), fill="black", width=3)
draw.line((35, 20, 35, 130), fill="black", width=3)
draw.line((50, 110, 140, 75, 230, 90, 315, 35), fill="#1f77b4", width=6)
draw.text((85, 135), "Deterministic fixture chart", fill="black")
buffer = BytesIO()
image.save(buffer, format="PNG")
buffer.seek(0)
page.drawImage(ImageReader(buffer), 72, 340, width=360, height=160, mask="auto")
page.setFont("Helvetica", 10)
page.drawString(72, 322, "Figure 1. Synthetic trend chart.")
page.showPage()
page.save()
if __name__ == "__main__":
main()
@@ -0,0 +1,60 @@
[
{
"type": "text",
"text": "The response of flow duration curves to afforestation ",
"text_level": 1,
"bbox": [
62,
480,
946,
904
],
"page_idx": 0
},
{
"type": "image",
"img_path": "images/a8ecda1c69b27e4f79fce1589175a9d721cbdc1cf78b4cc06a015f3746f6b9d8.jpg",
"img_caption": [
"Fig. 1. Annual flow duration curves of daily flows from Pine Creek, Australia, 1989–2000. "
],
"img_footnote": [],
"bbox": [
62,
480,
946,
904
],
"page_idx": 1
},
{
"type": "equation",
"img_path": "images/181ea56ef185060d04bf4e274685f3e072e922e7b839f093d482c29bf89b71e8.jpg",
"text": "$$\nQ _ { \\% } = f ( P ) + g ( T )\n$$",
"text_format": "latex",
"bbox": [
62,
480,
946,
904
],
"page_idx": 2
},
{
"type": "table",
"img_path": "images/e3cb413394a475e555807ffdad913435940ec637873d673ee1b039e3bc3496d0.jpg",
"table_caption": [
"Table 2 Significance of the rainfall and time terms "
],
"table_footnote": [
"indicates that the rainfall term was significant at the $5 \\%$ level, $T$ indicates that the time term was significant at the $5 \\%$ level, \\* represents significance at the $10 \\%$ level, and na denotes too few data points for meaningful analysis. "
],
"table_body": "<html><body><table><tr><td rowspan=\"2\">Site</td><td colspan=\"10\">Percentile</td></tr><tr><td>10</td><td>20</td><td>30</td><td>40</td><td>50</td><td>60</td><td>70</td><td>80</td><td>90</td><td>100</td></tr><tr><td>Traralgon Ck</td><td>P</td><td>P,*</td><td>P</td><td>P</td><td>P,</td><td>P,</td><td>P,</td><td>P,</td><td>P</td><td>P</td></tr><tr><td>Redhill</td><td>P,T</td><td>P,T</td><td>,*</td><td>**</td><td>P.T</td><td>P,*</td><td>P*</td><td>P*</td><td>*</td><td>,*</td></tr><tr><td>Pine Ck</td><td></td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>T</td><td>T</td><td>na</td><td>na</td></tr><tr><td>Stewarts Ck 5</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P.T</td><td>P.T</td><td>P,T</td><td>na</td><td>na</td><td>na</td></tr><tr><td>Glendhu 2</td><td>P</td><td>P,T</td><td>P,*</td><td>P,T</td><td>P.T</td><td>P,ns</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td></tr><tr><td>Cathedral Peak 2</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>*,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td></tr><tr><td>Cathedral Peak 3</td><td>P.T</td><td>P.T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td></tr><tr><td>Lambrechtsbos A</td><td>P,T</td><td>P</td><td>P</td><td>P,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>T</td></tr><tr><td>Lambrechtsbos B</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>T</td></tr><tr><td>Biesievlei</td><td>P,T</td><td>P.T</td><td>P,T</td><td>P,T</td><td>*,T</td><td>*,T</td><td>T</td><td>T</td><td>P,T</td><td>P,T</td></tr></table></body></html>",
"bbox": [
62,
480,
946,
904
],
"page_idx": 5
}
]
@@ -0,0 +1,10 @@
{
"commit": "61cc6886fe3edda8aa1c5b8bd2b6eaedddb8af99",
"content_sha256": "e3a09b50a8a902a584452ca7085533fa6fe294bffe400c0dcabfdbe0339b92b7",
"fixture_schema": 1,
"kind": "official-legacy-schema-example",
"note": "Exact official documentation example; not a live parser capture.",
"repository": "https://github.com/opendatalab/MinerU.git",
"source_path": "docs/en/reference/output_files.md",
"source_section": "#### Content List (content_list.json)"
}
@@ -0,0 +1,70 @@
[
{
"type": "text",
"text": "DeepTutor LightRAG Bridge Fixture",
"text_level": 2,
"bbox": [
114,
70,
619,
97
],
"page_idx": 0
},
{
"type": "text",
"text": "A short paragraph preserves text and heading hierarchy.",
"bbox": [
111,
114,
568,
133
],
"page_idx": 0
},
{
"type": "equation",
"img_path": "images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg",
"text": "$$\nE = m c ^ { \\wedge } 2\n$$",
"text_format": "latex",
"bbox": [
434,
160,
562,
181
],
"page_idx": 0
},
{
"type": "table",
"img_path": "images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg",
"table_caption": [
"Table 1. Retrieval engine paths"
],
"table_footnote": [],
"table_body": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",
"bbox": [
114,
251,
607,
314
],
"page_idx": 0
},
{
"type": "chart",
"img_path": "images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg",
"content": "",
"chart_caption": [
"Figure 1. Synthetic trend chart."
],
"chart_footnote": [],
"bbox": [
166,
386,
658,
556
],
"page_idx": 0
}
]
@@ -0,0 +1,101 @@
[
[
{
"type": "title",
"content": {
"title_content": [
{
"type": "text",
"content": "DeepTutor LightRAG Bridge Fixture"
}
],
"level": 2
},
"bbox": [
114,
70,
619,
97
]
},
{
"type": "paragraph",
"content": {
"paragraph_content": [
{
"type": "text",
"content": "A short paragraph preserves text and heading hierarchy."
}
]
},
"bbox": [
111,
114,
568,
133
]
},
{
"type": "equation_interline",
"content": {
"math_content": "E = m c ^ { \\wedge } 2",
"math_type": "latex",
"image_source": {
"path": "images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg"
}
},
"bbox": [
434,
160,
562,
181
]
},
{
"type": "table",
"content": {
"image_source": {
"path": "images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg"
},
"table_caption": [
{
"type": "text",
"content": "Table 1. Retrieval engine paths"
}
],
"table_footnote": [],
"html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",
"table_type": "simple_table",
"table_nest_level": 1
},
"bbox": [
114,
251,
607,
314
]
},
{
"type": "chart",
"content": {
"image_source": {
"path": "images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg"
},
"content": "",
"chart_caption": [
{
"type": "text",
"content": "Figure 1. Synthetic trend chart."
}
],
"chart_footnote": []
},
"bbox": [
166,
386,
658,
556
]
}
]
]
@@ -0,0 +1,141 @@
[
{
"layout_dets": [
{
"cls_id": 17,
"label": "paragraph_title",
"score": 0.5515,
"bbox": [
195,
156,
1055,
215
],
"index": 1
},
{
"cls_id": 22,
"label": "text",
"score": 0.9291,
"bbox": [
191,
255,
968,
295
],
"index": 2
},
{
"cls_id": 5,
"label": "display_formula",
"score": 0.9417,
"bbox": [
740,
353,
958,
401
],
"index": 3,
"latex": "E = m c ^ { \\wedge } 2"
},
{
"cls_id": 7,
"label": "figure_title",
"score": 0.9427,
"bbox": [
193,
477,
653,
517
],
"index": 4
},
{
"cls_id": 21,
"label": "table",
"score": 0.9627,
"bbox": [
197,
554,
1034,
694
],
"index": 5,
"html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>"
},
{
"cls_id": 3,
"label": "chart",
"score": 0.9352,
"bbox": [
284,
851,
1122,
1226
],
"index": 6
},
{
"cls_id": 7,
"label": "figure_title",
"score": 0.9393,
"bbox": [
193,
1278,
583,
1317
],
"index": 7
},
{
"label": "ocr_text",
"bbox": [
200,
159,
1051,
212
],
"score": 1.0,
"text": ""
},
{
"label": "ocr_text",
"bbox": [
200,
260,
962,
289
],
"score": 1.0,
"text": ""
},
{
"label": "ocr_text",
"bbox": [
199,
478,
648,
513
],
"score": 1.0,
"text": ""
},
{
"label": "ocr_text",
"bbox": [
199,
1283,
578,
1313
],
"score": 1.0,
"text": ""
}
],
"page_info": {
"page_no": 0,
"width": 1700,
"height": 2200
}
}
]
@@ -0,0 +1,57 @@
%PDF-1.7
%¡³Å×
1 0 obj
<</Pages 2 0 R /Type/Catalog>>
endobj
2 0 obj
<</Count 1/Kids[ 4 0 R ]/Type/Pages>>
endobj
3 0 obj
<</CreationDate(D:20260828225606)/Creator(PDFium)/Producer(PDFium)>>
endobj
4 0 obj
<</Contents 5 0 R /MediaBox[ 0 0 612 792]/Parent 2 0 R /Resources<</Font 6 0 R /ProcSet[/PDF/Text/ImageB/ImageC/ImageI]/XObject<</FormXob.1fe5b52c6a9de28e0822ad9f49443d36 10 0 R >>>>/Rotate 0/Trans<<>>/Type/Page>>
endobj
5 0 obj
<</Filter[/ASCII85Decode/FlateDecode]/Length 492>>stream
GasIc9i'e''YNU1b]2SQifBQ#^k&M-05.a$5&`i/PLnHc9o<^9q"JPOr;oul7*3Vc1?3ZK0bj.erNfZ.'90%1"67`90UYStHedkea#R7iE6`KH`7[oFR`E$j?K'M#BW^/YkAfr/)]imHA)^eM&8(>n]Qq)=IY#3q-q?eY4,TQ#<EA-Gq%aq(q1,mCVX\88Z1bOJ^SMA@]a'q5L*]d1[XiS^NN_\=rmaelRtRgt01uU/)GKU=K,(D!r`+^QG\f8dBJX!.=H3UnhU0n*6#GXcMEujMSEREG[uob!0GQ>9&s!XdHk5u%!>c!Ppr)'<S:d*\_m)8>8!-n"GX%UjO*E!Z)7e@>BMkDaF+4\e'M%$;)#$-CM=(/Q?^booG0E/t\F$9_CF3"8&E>j,&Mbq]FuAU`lD^99CdFilLf_`XCZ6WT-0M-H0B?5-;%&(lQi6eAH;]cE88"=#->moDmc-eV/-T)uG`$iM=l[EamNMH<>SP\d~>
endstream
endobj
6 0 obj
<</F1 7 0 R /F2 8 0 R /F3 9 0 R >>
endobj
7 0 obj
<</BaseFont/Helvetica/Encoding/WinAnsiEncoding/Name/F1/Subtype/Type1/Type/Font>>
endobj
8 0 obj
<</BaseFont/Helvetica-Bold/Encoding/WinAnsiEncoding/Name/F2/Subtype/Type1/Type/Font>>
endobj
9 0 obj
<</BaseFont/Times-Italic/Encoding/WinAnsiEncoding/Name/F3/Subtype/Type1/Type/Font>>
endobj
10 0 obj
<</BitsPerComponent 8/ColorSpace/DeviceRGB/Filter[/ASCII85Decode/FlateDecode]/Height 160/Length 2327/Subtype/Image/Type/XObject/Width 360>>stream
Gb"0VgP\dS"2OFsarrd0SFYs)>R3(>.+8SoEf.r'jHLAYJ6.VK7>c,AU*ph8$Z95-`hAXG%8BQ+jDZD*`8hWprUm=bh0s#*g!?affmBp?kL5W\=_lSl^\+\cGCFn1H9++gzzzzz.f&CKotD"\208qV9/hC2F9@=l2h8D[",KT/J@K\'LeB[W\9%h/9/hC2F9@=l2h8D["8_6=s1)>%>GsF8J6iW&./[$4H`8IMJDM`8L2I!VFX]cie"I]l96\e1%A6[S@cT*]\cFsf(r^S!.^R>IV&N6^@[*].:mPZ^"hF`2'VdG>J7=f^4eWf+;2h*q%HnLcQumtN;iG&0%J!1LH:Kp8-cP9Wh&qIeUQ9ML>d;N:(V2n]-q8^6%J%:iUOVM4RAUo#:,g6JbD[pu%5LL0W_,4k*mpoEh&o?)UGd4HbRfc&d1%ir0ksB@83=eh4l%6o/2QQ[2b5C:W$C+@FY#?6:,b][`CL'd+>#-#P!_0!5/g&2h&tZE,Csrh`);Q4dLD@21m1Nk8/fH<52@>Y'I+?7UY!/urQ?r@7<Bb,mrgR5Wp-5s4kGl>Lu.s;4MWf%NITID>aPfsaFd)6h5Htb`@sS%Sk5sH7]BSR,)<KOcXY90h'gkKH*&?Wj^aaHV]22s-[SihT%0!7CcFGAkAJdbP3/tol+M/\b%EYr2An;UP2tLD]o]:4UhIbZUEmsl'Dbd*\rkX5eT9t)8P1'[4d>>Oe:%0m<FSUaZ0+f[XEGi+\Yu1h--=]dcEiIP,MNTb?DqF,4RN'f7Q9D&kGh\ucTET'h@4CAh^JbLV6h1Jh5V(s.SF&+]XN$W(_fV92nZLhj8%k@o"-%]C#NDbIO)?@()W-88aD+95k65!)i=Z1;>4tL"f+m6]:g(';RPtJ>X7#nZ5[fbfhd<==C=D6<3I6]!EiE^DC>^"><d9u/g)P<V&P9m\^Hg^a9CX'n%'YYOCti0@=\H$<i6ne^1X+QidOX"%%pt=;:R`2P,9&1(KCmb\__J(HM7Le?etas4[A;r"q[,=!-.6-&=787ETmZ=QYleCklq]cD?+\@"q[,=!-.6-&=787ETmZ=QYleCr<:\<]r-=OeGJ2j:=X^VpJno!+66;4k</eF!!#tk>?fjuK*OVhqGco&J\2g\FQe;[$Pk@"3.Lr*F6ChkGM%HK#PrJ+f%/E9-Vqb<)dTiApBK*D9fm[nkei/d]0!*T2d^=\aH<`fn+RcOqC50iNfK-cQBk11/lb*:Q?mf';56VRbB\CdmKr4MoUpMf?g1(A*]5i6Ie`D@_hJVY(GBZ@C:\opIe`cRIJX3Y*4TP$P1!X`)7FA7&q8h1gKV.)SMFd!WDf_3Ocq.g5'#^TQOAM,4aZlZ2`K'O2='hpbJegh*BVj!cnK+XSEne1(G8nDqsN:P[;4BKePZ,$gUD*rD[^E?E*2npQS2^?_nn-0Y$;8PgUD)cJ,Xi[GtRNQ])T(2.sp*h&8'4X)%@`?MSc-X0k3]CGb`_'hZ.1SnPoA\oB3W'j0igZG44;$nCLaF?Ho')]D/V9]7p_3Ep_SgBRB7,_;TpKGJJ_0@HtORq/X?*$!f.t4rHeQX1c2pd\KIRHcM'_oD/"@[^NW()`Ms>s3qO.DVDJ^_M&A+j6YI*4*Ks=*C@.'k09A,T*GlJ/6fQaliCD#$hn"OFChWp^*O]7e#-!:+b[&V\T?s4qtGg7(-`T#%5OgUQ2^XQlbEF3_;D+bSbh[(YJO^ZG7>KLm.]u+d2>7aU+_7O6shL9ZXMJ+Nut.a&L0aZn(kX%o9qOPDVVbLj]eI=M%_99q!fSFKM*$Z(:<]HLCYI:oCp4^(Yp)C$m.Yqg*ka+g!Q(uDWq^!mS9B<]kc6&E4.BsmF2S#VtcOkFmIWLjib]*+91`_\+&#=g>BVm]D/T;]=Mf[fI0GGZ?sK'_hWiJ_Cs^aY5\CspBj89D!^&o5:co.4F,B2V8KAFF2,oTZD/psh9mGt?+Mk7,:msE]?3;QaG.P^*Br<*RlBfuc("%MXc&M,=0Gp^/G6o&#d^MsY.3<OmeH:H]XbR5HrfOrkSQC)CuM+B_cEsIIIZ=9Y]8gLRGGK!GB_I(fqGCEl1*fSiG=#Cr$ag*=AcH6[YBbT-Vf?@&RE,am-)Su[r_nN7un/Ss6SFF6%]B,%^U*VO:?pD%boXg)#]?\p$:4<eq?WHdaHS#hB!]G@`=4i.p&%meR.,<Ii^XmB^XZd%1NceNup#[['9<#oB5(5_pqhj>#k?b:jS9nM\b-^HT,d-gpo5bo]#Iq!D]7N4Ua5rTI@LGZD/psh9mJ5h7GV9H2[U4Tm4uEV"g=o%0-A.zzz!$og=!LY8KdJ~>
endstream
endobj
xref
0 11
0000000000 65535 f
0000000017 00000 n
0000000066 00000 n
0000000122 00000 n
0000000209 00000 n
0000000441 00000 n
0000001021 00000 n
0000001074 00000 n
0000001173 00000 n
0000001277 00000 n
0000001379 00000 n
trailer
<<
/Root 1 0 R
/Info 3 0 R
/Size 11/ID[<E919D9A2E5EDF6C6F2B6DA9CF2041B12><E919D9A2E5EDF6C6F2B6DA9CF2041B12>]>>
startxref
3884
%%EOF
@@ -0,0 +1,22 @@
{
"artifacts": {
"a5d0461c-c073-4d71-944c-e79759a67637_content_list.json": "e8e5bb9c00a6da26d9a7b93abd6938acf3145503ae734cd05831c56bd7e5e842",
"a5d0461c-c073-4d71-944c-e79759a67637_content_list_v2.json": "920ef83a39170889d001b75973293fc65b8a7c8ac0b309c807b7d2cdcf199284",
"a5d0461c-c073-4d71-944c-e79759a67637_model.json": "9574219a0d6f52303d4d46e15c01d19b02bd49b2674f542eebd729ad29af9e59",
"a5d0461c-c073-4d71-944c-e79759a67637_origin.pdf": "bf173e5d24d268a8a5a25766d190d2b01a124394c5e0e33094c08c6a9d8bbbc4",
"full.md": "e2861269e39a18874137029375666f79ea75af68d3ccbe490d112d1141368344",
"images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg": "a4542ec348a798c6a6dba4b89a4ab91d1b23c45b4c50bfaeb8303a4874e1e10d",
"images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg": "18c517e03a9b15f5e7748ab4187dd8cd349018f7582784425a03bb538c146691",
"images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg": "53eaf9d9acb37f7f885dd51d17f183590da9068d3fd26d9701b885cf4f8fc970",
"layout.json": "549cb6fcd708664adb081afa494781a54bea250e1d86acc7776049f2e2c35d63"
},
"authenticated": true,
"capture_schema": 1,
"captured_at_utc": "2026-08-28T14:56:16.031586+00:00",
"model_version": "pipeline",
"service": "https://mineru.net/api/v4",
"source": {
"path": "../original.pdf",
"sha256": "e2abd3404f3a03d90c36feec19786689892434e730841cbdbd2a1a28875f3a80"
}
}
@@ -0,0 +1,13 @@
## DeepTutor LightRAG Bridge Fixture
A short paragraph preserves text and heading hierarchy.
$$
E = m c ^ { \wedge } 2
$$
Table 1. Retrieval engine paths
<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>
![](images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg)
Figure 1. Synthetic trend chart.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

@@ -0,0 +1,552 @@
{
"pdf_info": [
{
"preproc_blocks": [
{
"score": 0.5515,
"bbox": [
70,
56,
379,
77
],
"index": 1,
"type": "title",
"lines": [
{
"bbox": [
72,
57,
378,
76
],
"spans": [
{
"bbox": [
72,
57,
378,
76
],
"type": "text",
"content": "DeepTutor LightRAG Bridge Fixture",
"score": 1.0
}
]
}
],
"level": 2
},
{
"score": 0.9291,
"bbox": [
68,
91,
348,
106
],
"index": 2,
"type": "text",
"lines": [
{
"bbox": [
72,
93,
346,
104
],
"spans": [
{
"bbox": [
72,
93,
346,
104
],
"type": "text",
"content": "A short paragraph preserves text and heading hierarchy.",
"score": 1.0
}
]
}
]
},
{
"score": 0.9417,
"bbox": [
266,
127,
344,
144
],
"index": 3,
"type": "interline_equation",
"lines": [
{
"bbox": [
266,
127,
344,
144
],
"spans": [
{
"bbox": [
266,
127,
344,
144
],
"type": "interline_equation",
"content": "E = m c ^ { \\wedge } 2",
"image_path": "4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg"
}
]
}
]
},
{
"type": "table",
"bbox": [
70,
199,
372,
249
],
"blocks": [
{
"score": 0.9427,
"bbox": [
69,
171,
235,
186
],
"index": 4,
"type": "table_caption",
"lines": [
{
"bbox": [
71,
172,
233,
184
],
"spans": [
{
"bbox": [
71,
172,
233,
184
],
"type": "text",
"content": "Table 1. Retrieval engine paths",
"score": 1.0
}
]
}
]
},
{
"score": 0.9627,
"bbox": [
70,
199,
372,
249
],
"index": 5,
"type": "table_body",
"lines": [
{
"bbox": [
70,
199,
372,
249
],
"spans": [
{
"bbox": [
70,
199,
372,
249
],
"type": "table",
"html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",
"image_path": "c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg"
}
]
}
]
}
],
"index": 5,
"score": 0.9627
},
{
"type": "chart",
"bbox": [
102,
306,
403,
441
],
"blocks": [
{
"score": 0.9352,
"bbox": [
102,
306,
403,
441
],
"index": 6,
"type": "chart_body",
"lines": [
{
"bbox": [
102,
306,
403,
441
],
"spans": [
{
"bbox": [
102,
306,
403,
441
],
"type": "chart",
"image_path": "f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg"
}
]
}
]
},
{
"score": 0.9393,
"bbox": [
69,
460,
209,
474
],
"index": 7,
"type": "chart_caption",
"lines": [
{
"bbox": [
71,
461,
208,
472
],
"spans": [
{
"bbox": [
71,
461,
208,
472
],
"type": "text",
"content": "Figure 1. Synthetic trend chart.",
"score": 1.0
}
]
}
]
}
],
"index": 6,
"score": 0.9352
}
],
"page_idx": 0,
"page_size": [
612,
792
],
"discarded_blocks": [],
"para_blocks": [
{
"score": 0.5515,
"bbox": [
70,
56,
379,
77
],
"index": 1,
"type": "title",
"lines": [
{
"bbox": [
72,
57,
378,
76
],
"spans": [
{
"bbox": [
72,
57,
378,
76
],
"type": "text",
"content": "DeepTutor LightRAG Bridge Fixture",
"score": 1.0
}
]
}
],
"level": 2
},
{
"score": 0.9291,
"bbox": [
68,
91,
348,
106
],
"index": 2,
"type": "text",
"lines": [
{
"bbox": [
72,
93,
346,
104
],
"spans": [
{
"bbox": [
72,
93,
346,
104
],
"type": "text",
"content": "A short paragraph preserves text and heading hierarchy.",
"score": 1.0
}
]
}
],
"bbox_fs": [
72,
93,
346,
104
]
},
{
"score": 0.9417,
"bbox": [
266,
127,
344,
144
],
"index": 3,
"type": "interline_equation",
"lines": [
{
"bbox": [
266,
127,
344,
144
],
"spans": [
{
"bbox": [
266,
127,
344,
144
],
"type": "interline_equation",
"content": "E = m c ^ { \\wedge } 2",
"image_path": "4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg"
}
]
}
]
},
{
"type": "table",
"bbox": [
70,
199,
372,
249
],
"blocks": [
{
"score": 0.9427,
"bbox": [
69,
171,
235,
186
],
"index": 4,
"type": "table_caption",
"lines": [
{
"bbox": [
71,
172,
233,
184
],
"spans": [
{
"bbox": [
71,
172,
233,
184
],
"type": "text",
"content": "Table 1. Retrieval engine paths",
"score": 1.0
}
]
}
]
},
{
"score": 0.9627,
"bbox": [
70,
199,
372,
249
],
"index": 5,
"type": "table_body",
"lines": [
{
"bbox": [
70,
199,
372,
249
],
"spans": [
{
"bbox": [
70,
199,
372,
249
],
"type": "table",
"html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",
"image_path": "c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg"
}
]
}
]
}
],
"index": 5,
"score": 0.9627
},
{
"type": "chart",
"bbox": [
102,
306,
403,
441
],
"blocks": [
{
"score": 0.9352,
"bbox": [
102,
306,
403,
441
],
"index": 6,
"type": "chart_body",
"lines": [
{
"bbox": [
102,
306,
403,
441
],
"spans": [
{
"bbox": [
102,
306,
403,
441
],
"type": "chart",
"image_path": "f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg"
}
]
}
]
},
{
"score": 0.9393,
"bbox": [
69,
460,
209,
474
],
"index": 7,
"type": "chart_caption",
"lines": [
{
"bbox": [
71,
461,
208,
472
],
"spans": [
{
"bbox": [
71,
461,
208,
472
],
"type": "text",
"content": "Figure 1. Synthetic trend chart.",
"score": 1.0
}
]
}
]
}
],
"index": 6,
"score": 0.9352
}
]
}
],
"_backend": "pipeline",
"_version_name": "3.4.4"
}
+91
View File
@@ -0,0 +1,91 @@
%PDF-1.3
%“Œ‹ž ReportLab Generated PDF document (opensource)
1 0 obj
<<
/F1 2 0 R /F2 3 0 R /F3 4 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font
>>
endobj
4 0 obj
<<
/BaseFont /Times-Italic /Encoding /WinAnsiEncoding /Name /F3 /Subtype /Type1 /Type /Font
>>
endobj
5 0 obj
<<
/BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter [ /ASCII85Decode /FlateDecode ] /Height 160 /Length 2327 /Subtype /Image
/Type /XObject /Width 360
>>
stream
Gb"0VgP\dS"2OFsarrd0SFYs)>R3(>.+8SoEf.r'jHLAYJ6.VK7>c,AU*ph8$Z95-`hAXG%8BQ+jDZD*`8hWprUm=bh0s#*g!?affmBp?kL5W\=_lSl^\+\cGCFn1H9++gzzzzz.f&CKotD"\208qV9/hC2F9@=l2h8D[",KT/J@K\'LeB[W\9%h/9/hC2F9@=l2h8D["8_6=s1)>%>GsF8J6iW&./[$4H`8IMJDM`8L2I!VFX]cie"I]l96\e1%A6[S@cT*]\cFsf(r^S!.^R>IV&N6^@[*].:mPZ^"hF`2'VdG>J7=f^4eWf+;2h*q%HnLcQumtN;iG&0%J!1LH:Kp8-cP9Wh&qIeUQ9ML>d;N:(V2n]-q8^6%J%:iUOVM4RAUo#:,g6JbD[pu%5LL0W_,4k*mpoEh&o?)UGd4HbRfc&d1%ir0ksB@83=eh4l%6o/2QQ[2b5C:W$C+@FY#?6:,b][`CL'd+>#-#P!_0!5/g&2h&tZE,Csrh`);Q4dLD@21m1Nk8/fH<52@>Y'I+?7UY!/urQ?r@7<Bb,mrgR5Wp-5s4kGl>Lu.s;4MWf%NITID>aPfsaFd)6h5Htb`@sS%Sk5sH7]BSR,)<KOcXY90h'gkKH*&?Wj^aaHV]22s-[SihT%0!7CcFGAkAJdbP3/tol+M/\b%EYr2An;UP2tLD]o]:4UhIbZUEmsl'Dbd*\rkX5eT9t)8P1'[4d>>Oe:%0m<FSUaZ0+f[XEGi+\Yu1h--=]dcEiIP,MNTb?DqF,4RN'f7Q9D&kGh\ucTET'h@4CAh^JbLV6h1Jh5V(s.SF&+]XN$W(_fV92nZLhj8%k@o"-%]C#NDbIO)?@()W-88aD+95k65!)i=Z1;>4tL"f+m6]:g(';RPtJ>X7#nZ5[fbfhd<==C=D6<3I6]!EiE^DC>^"><d9u/g)P<V&P9m\^Hg^a9CX'n%'YYOCti0@=\H$<i6ne^1X+QidOX"%%pt=;:R`2P,9&1(KCmb\__J(HM7Le?etas4[A;r"q[,=!-.6-&=787ETmZ=QYleCklq]cD?+\@"q[,=!-.6-&=787ETmZ=QYleCr<:\<]r-=OeGJ2j:=X^VpJno!+66;4k</eF!!#tk>?fjuK*OVhqGco&J\2g\FQe;[$Pk@"3.Lr*F6ChkGM%HK#PrJ+f%/E9-Vqb<)dTiApBK*D9fm[nkei/d]0!*T2d^=\aH<`fn+RcOqC50iNfK-cQBk11/lb*:Q?mf';56VRbB\CdmKr4MoUpMf?g1(A*]5i6Ie`D@_hJVY(GBZ@C:\opIe`cRIJX3Y*4TP$P1!X`)7FA7&q8h1gKV.)SMFd!WDf_3Ocq.g5'#^TQOAM,4aZlZ2`K'O2='hpbJegh*BVj!cnK+XSEne1(G8nDqsN:P[;4BKePZ,$gUD*rD[^E?E*2npQS2^?_nn-0Y$;8PgUD)cJ,Xi[GtRNQ])T(2.sp*h&8'4X)%@`?MSc-X0k3]CGb`_'hZ.1SnPoA\oB3W'j0igZG44;$nCLaF?Ho')]D/V9]7p_3Ep_SgBRB7,_;TpKGJJ_0@HtORq/X?*$!f.t4rHeQX1c2pd\KIRHcM'_oD/"@[^NW()`Ms>s3qO.DVDJ^_M&A+j6YI*4*Ks=*C@.'k09A,T*GlJ/6fQaliCD#$hn"OFChWp^*O]7e#-!:+b[&V\T?s4qtGg7(-`T#%5OgUQ2^XQlbEF3_;D+bSbh[(YJO^ZG7>KLm.]u+d2>7aU+_7O6shL9ZXMJ+Nut.a&L0aZn(kX%o9qOPDVVbLj]eI=M%_99q!fSFKM*$Z(:<]HLCYI:oCp4^(Yp)C$m.Yqg*ka+g!Q(uDWq^!mS9B<]kc6&E4.BsmF2S#VtcOkFmIWLjib]*+91`_\+&#=g>BVm]D/T;]=Mf[fI0GGZ?sK'_hWiJ_Cs^aY5\CspBj89D!^&o5:co.4F,B2V8KAFF2,oTZD/psh9mGt?+Mk7,:msE]?3;QaG.P^*Br<*RlBfuc("%MXc&M,=0Gp^/G6o&#d^MsY.3<OmeH:H]XbR5HrfOrkSQC)CuM+B_cEsIIIZ=9Y]8gLRGGK!GB_I(fqGCEl1*fSiG=#Cr$ag*=AcH6[YBbT-Vf?@&RE,am-)Su[r_nN7un/Ss6SFF6%]B,%^U*VO:?pD%boXg)#]?\p$:4<eq?WHdaHS#hB!]G@`=4i.p&%meR.,<Ii^XmB^XZd%1NceNup#[['9<#oB5(5_pqhj>#k?b:jS9nM\b-^HT,d-gpo5bo]#Iq!D]7N4Ua5rTI@LGZD/psh9mJ5h7GV9H2[U4Tm4uEV"g=o%0-A.zzz!$og=!LY8KdJ~>endstream
endobj
6 0 obj
<<
/Contents 10 0 R /MediaBox [ 0 0 612 792 ] /Parent 9 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /XObject <<
/FormXob.1fe5b52c6a9de28e0822ad9f49443d36 5 0 R
>>
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
7 0 obj
<<
/PageMode /UseNone /Pages 9 0 R /Type /Catalog
>>
endobj
8 0 obj
<<
/Author (DeepTutor contributors) /CreationDate (D:20000101000000+00'00') /Creator (anonymous) /Keywords () /ModDate (D:20000101000000+00'00') /Producer (ReportLab PDF Library - \(opensource\))
/Subject (unspecified) /Title (DeepTutor LightRAG Bridge Fixture) /Trapped /False
>>
endobj
9 0 obj
<<
/Count 1 /Kids [ 6 0 R ] /Type /Pages
>>
endobj
10 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 492
>>
stream
GasIc9i'e''YNU1b]2SQifBQ#^k&M-05.a$5&`i/PLnHc9o<^9q"JPOr;oul7*3Vc1?3ZK0bj.erNfZ.'90%1"67`90UYStHedkea#R7iE6`KH`7[oFR`E$j?K'M#BW^/YkAfr/)]imHA)^eM&8(>n]Qq)=IY#3q-q?eY4,TQ#<EA-Gq%aq(q1,mCVX\88Z1bOJ^SMA@]a'q5L*]d1[XiS^NN_\=rmaelRtRgt01uU/)GKU=K,(D!r`+^QG\f8dBJX!.=H3UnhU0n*6#GXcMEujMSEREG[uob!0GQ>9&s!XdHk5u%!>c!Ppr)'<S:d*\_m)8>8!-n"GX%UjO*E!Z)7e@>BMkDaF+4\e'M%$;)#$-CM=(/Q?^booG0E/t\F$9_CF3"8&E>j,&Mbq]FuAU`lD^99CdFilLf_`XCZ6WT-0M-H0B?5-;%&(lQi6eAH;]cE88"=#->moDmc-eV/-T)uG`$iM=l[EamNMH<>SP\d~>endstream
endobj
xref
0 11
0000000000 65535 f
0000000061 00000 n
0000000112 00000 n
0000000219 00000 n
0000000331 00000 n
0000000441 00000 n
0000002959 00000 n
0000003216 00000 n
0000003284 00000 n
0000003583 00000 n
0000003642 00000 n
trailer
<<
/ID
[<1032306cdd7e2f90b2233ccd4ed2d1e2><1032306cdd7e2f90b2233ccd4ed2d1e2>]
% ReportLab generated PDF document -- digest (opensource)
/Info 8 0 R
/Root 7 0 R
/Size 11
>>
startxref
4225
%%EOF
+76
View File
@@ -167,3 +167,79 @@ def test_capture_is_empty_when_no_backend_is_available(monkeypatch: pytest.Monke
assert snapshot.processes == ()
assert snapshot.total_rss_bytes == 0
def test_scan_psutil_falls_back_when_children_raises_permission_error(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""HarmonyOS: psutil.children() raises raw PermissionError on /proc/1/stat (#1076)."""
class _PsutilError(Exception):
pass
class _BoomProcess:
def children(self, recursive: bool = False):
raise PermissionError("[Errno 13] Permission denied: '/proc/1/stat'")
class _FakePsutil:
Error = _PsutilError
AccessDenied = _PsutilError
@staticmethod
def pid_exists(pid: int) -> bool:
return True
@staticmethod
def Process(pid: int | None = None):
return _BoomProcess()
fallback = (
[memory_probe.ProcessMemory(pid=os.getpid(), label="backend", rss_bytes=1024)],
True,
)
monkeypatch.setattr(memory_probe.sys, "platform", "linux")
monkeypatch.setattr(memory_probe, "_scan_proc", lambda: fallback)
processes, partial = memory_probe._scan_psutil(_FakePsutil())
assert processes == fallback[0]
assert partial is True
def test_scan_psutil_self_path_when_permission_error_off_linux(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class _PsutilError(Exception):
pass
class _BoomProcess:
def children(self, recursive: bool = False):
raise PermissionError("denied")
@property
def pid(self) -> int:
return os.getpid()
def memory_info(self):
return type("MI", (), {"rss": 2048})()
class _FakePsutil:
Error = _PsutilError
AccessDenied = _PsutilError
@staticmethod
def pid_exists(pid: int) -> bool:
return True
@staticmethod
def Process(pid: int | None = None):
return _BoomProcess()
monkeypatch.setattr(memory_probe.sys, "platform", "darwin")
processes, partial = memory_probe._scan_psutil(_FakePsutil())
assert len(processes) == 1
assert processes[0].pid == os.getpid()
assert processes[0].rss_bytes == 2048
assert partial is True
@@ -0,0 +1,71 @@
"""Tests for role-aware Jina embedding requests."""
from __future__ import annotations
import pytest
from deeptutor.services.embedding.adapters.base import EmbeddingRequest
from deeptutor.services.embedding.adapters.jina import JinaEmbeddingAdapter
@pytest.mark.asyncio
async def test_jina_adapter_maps_retrieval_roles_to_tasks(monkeypatch) -> None:
captured: dict[str, object] = {}
class _Response:
status_code = 200
text = ""
def raise_for_status(self) -> None:
return None
def json(self) -> dict[str, object]:
return {
"data": [{"embedding": [0.1, 0.2]}],
"model": "jina-embeddings-v3",
}
class _AsyncClient:
def __init__(self, **_kwargs) -> None:
pass
async def __aenter__(self):
return self
async def __aexit__(self, *_args) -> None:
return None
async def post(self, url: str, *, json: dict[str, object], **_kwargs):
captured["url"] = url
captured["payload"] = json
return _Response()
monkeypatch.setattr(
"deeptutor.services.embedding.adapters.jina.httpx.AsyncClient", _AsyncClient
)
adapter = JinaEmbeddingAdapter(
{
"api_key": "test-key",
"base_url": "https://api.jina.ai/v1/embeddings",
"model": "jina-embeddings-v3",
"dimensions": 2,
}
)
document_request = EmbeddingRequest(
texts=["document text"],
model="jina-embeddings-v3",
dimensions=2,
input_type="search_document",
)
await adapter.embed(document_request)
assert captured["payload"]["task"] == "retrieval.passage"
query_request = EmbeddingRequest(
texts=["query text"],
model="jina-embeddings-v3",
dimensions=2,
input_type="search_query",
)
await adapter.embed(query_request)
assert captured["payload"]["task"] == "retrieval.query"
+25 -7
View File
@@ -103,12 +103,13 @@ def _provider(model: str) -> OpenAICompatProvider:
)
def test_only_supported_deepseek_model_uses_responses_for_native_search() -> None:
def test_supported_deepseek_models_use_responses_for_native_search() -> None:
assert _provider("deepseek-v4-flash")._should_use_responses_api(
"deepseek-v4-flash", None, _TOOLS
)
assert not _provider("deepseek-v4-pro")._should_use_responses_api(
"deepseek-v4-pro", None, _TOOLS
assert _provider("deepseek-v4-pro")._should_use_responses_api("deepseek-v4-pro", None, _TOOLS)
assert not _provider("deepseek-reasoner")._should_use_responses_api(
"deepseek-reasoner", None, _TOOLS
)
assert not _provider("deepseek-v4-flash")._should_use_responses_api(
"deepseek-v4-flash", None, None
@@ -125,6 +126,15 @@ def test_native_mapping_is_model_scoped() -> None:
None,
None,
)
reasoner_body = _provider("deepseek-reasoner")._build_responses_body(
[{"role": "user", "content": "latest news"}],
_TOOLS,
"deepseek-reasoner",
256,
0.7,
None,
None,
)
pro_body = _provider("deepseek-v4-pro")._build_responses_body(
[{"role": "user", "content": "latest news"}],
_TOOLS,
@@ -135,10 +145,11 @@ def test_native_mapping_is_model_scoped() -> None:
None,
)
assert flash_body["tools"] == [{"type": "web_search"}]
assert pro_body["tools"][0]["type"] == "function"
assert pro_body["tools"] == [{"type": "web_search"}]
assert reasoner_body["tools"][0]["type"] == "function"
def test_agent_client_routes_only_supported_model_through_provider_adapter(monkeypatch) -> None:
def test_agent_client_routes_supported_models_through_provider_adapter(monkeypatch) -> None:
sentinel = object()
monkeypatch.setattr(
client_module,
@@ -153,14 +164,21 @@ def test_agent_client_routes_only_supported_model_through_provider_adapter(monke
api_key="k",
base_url="https://api.deepseek.com",
)
reasoner = LLMClientConfig(
binding="deepseek",
model="deepseek-reasoner",
api_key="k",
base_url="https://api.deepseek.com",
)
assert client_module._build_native_provider_adapter(flash, spec) is sentinel
pro = LLMClientConfig(
binding="deepseek",
model="deepseek-v4-pro",
api_key="k",
base_url="https://api.deepseek.com",
)
assert client_module._build_native_provider_adapter(flash, spec) is sentinel
assert client_module._build_native_provider_adapter(pro, spec) is None
assert client_module._build_native_provider_adapter(pro, spec) is sentinel
assert client_module._build_native_provider_adapter(reasoner, spec) is None
@pytest.mark.asyncio
@@ -98,6 +98,29 @@ def test_services_deepseek_v4_flash_disables_thinking_by_default() -> None:
assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
def test_openai_binding_deepseek_v4_flash_disables_thinking_by_default() -> None:
"""#1058: openai binding pointed at DeepSeek must still disable flash thinking."""
kwargs = _build_services_kwargs(
"openai",
None,
model="deepseek-v4-flash",
)
assert "reasoning_effort" not in kwargs
assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
def test_openai_binding_deepseek_v4_pro_enables_thinking_by_default() -> None:
kwargs = _build_services_kwargs(
"openai",
None,
model="deepseek-v4-pro",
)
assert kwargs["reasoning_effort"] == "high"
assert kwargs["extra_body"] == {"thinking": {"type": "enabled"}}
def test_services_deepseek_v4_pro_enables_thinking_by_default() -> None:
kwargs = _build_services_kwargs("deepseek", None)
@@ -1,5 +1,6 @@
from __future__ import annotations
import hashlib
import json
from pathlib import Path
@@ -24,6 +25,55 @@ def _signature(model: str = "embed-a", dim: int = 1024) -> EmbeddingSignature:
)
def test_legacy_role_naive_signature_hash_is_stable() -> None:
fields = {
"api_version": "",
"base_url": "https://api.openai.com/v1/embeddings",
"binding": "openai",
"dimension": 1536,
"model": "text-embedding-3-small",
}
signature = EmbeddingSignature(
binding=fields["binding"],
model=fields["model"],
dimension=fields["dimension"],
base_url=fields["base_url"],
api_version="",
)
expected_hash = hashlib.sha256(
json.dumps(fields, sort_keys=True, ensure_ascii=False).encode("utf-8")
).hexdigest()[:16]
assert signature.hash() == expected_hash
assert signature.role_semantics == ""
def test_jina_role_semantics_changes_signature() -> None:
from types import SimpleNamespace
from deeptutor.services.rag.embedding_signature import signature_from_config
config = SimpleNamespace(
binding="jina",
model="jina-embeddings-v3",
dim=1024,
base_url="https://api.jina.ai/v1/embeddings",
effective_url="https://api.jina.ai/v1/embeddings",
api_version="",
)
legacy_signature = EmbeddingSignature(
binding="jina",
model="jina-embeddings-v3",
dimension=1024,
base_url="https://api.jina.ai/v1/embeddings",
api_version="",
)
active_signature = signature_from_config(config)
assert active_signature.role_semantics == "jina-task"
assert active_signature.hash() != legacy_signature.hash()
def test_resolve_storage_dir_for_write_allocates_flat_version_dirs(tmp_path: Path) -> None:
kb_dir = tmp_path / "kb"
sig = _signature()
+337
View File
@@ -0,0 +1,337 @@
from __future__ import annotations
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import pytest
from deeptutor.services.parsing import cache as parsing_cache
from deeptutor.services.parsing.types import ParsedDocument
from deeptutor.services.rag.pipelines.lightrag import ingress, sidecar
FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "lightrag_bridge"
REQUIRES_LIGHTRAG = pytest.mark.skipif(
importlib.util.find_spec("lightrag") is None,
reason="requires the optional rag-lightrag extra",
)
def _structured(asset_dir: Path | None = None) -> ParsedDocument:
return ParsedDocument(
markdown="# Fixture\n\nBody",
blocks=[
{
"type": "text",
"text": "Fixture",
"text_level": 1,
"page_idx": 0,
"bbox": [1, 2, 3, 4],
},
{"type": "text", "text": "Body", "page_idx": 0},
{"type": "list", "list_items": ["one", "two"], "page_idx": 0},
{
"type": "code",
"code_body": "print('ok')",
"code_caption": ["Fixture code"],
"code_footnote": ["Code note"],
"page_idx": 0,
},
{
"type": "table",
"table_body": "<table><tr><td>A</td></tr></table>",
"table_caption": ["Table caption"],
"page_idx": 1,
},
{
"type": "image",
"img_path": "images/chart.png",
"image_caption": ["Chart caption"],
"page_idx": 1,
},
{"type": "equation", "text": "x^2", "page_idx": 1},
],
asset_dir=asset_dir,
source_hash="source-sha",
parser_signature="mineru-signature",
engine="mineru",
)
def test_freeze_is_an_independent_digest_verified_bundle(tmp_path: Path) -> None:
source = tmp_path / "paper.pdf"
source.write_bytes(b"original pdf")
assets = tmp_path / "parser-assets"
(assets / "images").mkdir(parents=True)
original_asset = assets / "images" / "chart.png"
original_asset.write_bytes(b"image")
working = tmp_path / "version-1"
staged = ingress.freeze_document(working, source, _structured(assets))
manifest, bundle = ingress.load_verified_bundle(working, "paper.pdf")
assert staged.source_path.read_bytes() == b"original pdf"
assert os.stat(staged.source_path).st_ino != os.stat(source).st_ino
frozen_asset = bundle / manifest["assets"][0]["path"]
assert frozen_asset.read_bytes() == b"image"
assert os.stat(frozen_asset).st_ino != os.stat(original_asset).st_ino
assert manifest["process_options"] == "Pite"
assert manifest["chunk_options"] == {"paragraph_semantic": {"chunk_token_size": 1200}}
source.write_bytes(b"mutated pdf")
original_asset.write_bytes(b"mutated image")
assert staged.source_path.read_bytes() == b"original pdf"
assert frozen_asset.read_bytes() == b"image"
ingress.load_verified_bundle(working, "paper.pdf")
def test_absolute_cached_image_path_is_rewritten_to_frozen_asset(tmp_path: Path) -> None:
source = tmp_path / "paper.pdf"
source.write_bytes(b"pdf")
assets = tmp_path / "images"
assets.mkdir()
image = assets / "figure.png"
image.write_bytes(b"image")
parsed = ParsedDocument(
markdown="figure",
blocks=[{"type": "image", "img_path": str(image)}],
asset_dir=assets,
engine="mineru",
)
staged = ingress.freeze_document(tmp_path / "version-1", source, parsed)
manifest, bundle = ingress.load_verified_bundle(tmp_path / "version-1", staged.canonical_name)
frozen_blocks = json.loads((bundle / manifest["blocks"]["path"]).read_text())
assert frozen_blocks[0]["img_path"] == "figure.png"
assert parsed.blocks[0]["img_path"] == str(image)
assert (bundle / "assets" / "figure.png").read_bytes() == b"image"
def test_bundle_tamper_and_unsafe_names_fail_closed(tmp_path: Path) -> None:
source = tmp_path / "notes.md"
source.write_text("notes", encoding="utf-8")
working = tmp_path / "version-1"
staged = ingress.freeze_document(
working,
source,
ParsedDocument(markdown="notes", engine="text_only", source_hash="h", parser_signature="s"),
)
assert staged.process_options == "F"
(staged.bundle_dir / "markdown.utf8").write_text("tampered", encoding="utf-8")
with pytest.raises(ingress.IngressError, match="Digest mismatch"):
ingress.load_verified_bundle(working, "notes.md")
with pytest.raises(ingress.IngressError, match="Invalid canonical basename"):
ingress.load_verified_bundle(working, "../notes.md")
def test_bundle_payload_rejects_a_symlinked_parent(tmp_path: Path) -> None:
source = tmp_path / "notes.md"
source.write_text("notes", encoding="utf-8")
working = tmp_path / "version-1"
staged = ingress.freeze_document(
working,
source,
ParsedDocument(markdown="notes", engine="text_only"),
)
outside = tmp_path / "outside"
outside.mkdir()
(outside / "payload").write_text("notes", encoding="utf-8")
markdown = staged.bundle_dir / "markdown.utf8"
markdown.unlink()
nested = staged.bundle_dir / "nested"
nested.symlink_to(outside, target_is_directory=True)
manifest = json.loads(staged.manifest_path.read_text(encoding="utf-8"))
manifest["markdown"]["path"] = "nested/payload"
staged.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
with pytest.raises(ingress.IngressError, match="symbolic link"):
ingress.load_verified_bundle(working, "notes.md")
def test_source_and_assets_reject_links(tmp_path: Path) -> None:
source = tmp_path / "source.pdf"
source.write_bytes(b"pdf")
hardlink = tmp_path / "hardlink.pdf"
os.link(source, hardlink)
with pytest.raises(ingress.IngressError, match="hard-linked"):
ingress.freeze_document(tmp_path / "version-hardlink", source, _structured())
ordinary = tmp_path / "ordinary.pdf"
ordinary.write_bytes(b"pdf")
assets = tmp_path / "assets"
assets.mkdir()
(assets / "outside.png").write_bytes(b"image")
(assets / "link.png").symlink_to(assets / "outside.png")
with pytest.raises(ingress.IngressError, match="symbolic link"):
ingress.freeze_document(tmp_path / "version-symlink", ordinary, _structured(assets))
def test_same_canonical_basename_is_rejected_before_enqueue(tmp_path: Path) -> None:
first = tmp_path / "a" / "same.md"
second = tmp_path / "b" / "same.md"
first.parent.mkdir()
second.parent.mkdir()
first.write_text("first", encoding="utf-8")
second.write_text("second", encoding="utf-8")
parsed = ParsedDocument(markdown="content", engine="text_only")
working = tmp_path / "version-1"
ingress.freeze_document(working, first, parsed)
with pytest.raises(ingress.IngressError, match="basename already exists"):
ingress.freeze_document(working, second, parsed)
@REQUIRES_LIGHTRAG
def test_sidecar_maps_structured_fields_and_positions(tmp_path: Path) -> None:
source = tmp_path / "paper.pdf"
source.write_bytes(b"pdf")
assets = tmp_path / "parser-assets"
(assets / "images").mkdir(parents=True)
(assets / "images" / "chart.png").write_bytes(b"image")
working = tmp_path / "version-1"
staged = ingress.freeze_document(working, source, _structured(assets))
manifest, bundle = ingress.load_verified_bundle(working, staged.canonical_name)
document = sidecar.build_ir(manifest, bundle)
assert document.document_name == "paper.pdf"
assert document.doc_title == "Fixture"
assert document.split_option == {"parser": "mineru", "parser_signature": "mineru-signature"}
assert len(document.assets) == 1
assert document.assets[0].source.read_bytes() == b"image"
block = document.blocks[0]
assert block.heading == "Fixture"
assert block.level == 1
assert "one\ntwo" in block.content_template
assert "print('ok')" in block.content_template
assert "Fixture code" in block.content_template
assert "Code note" in block.content_template
assert block.tables[0].html.startswith("<table>")
assert block.drawings[0].caption == "Chart caption"
assert block.equations[0].latex == "x^2"
assert block.positions[0].anchor == "1"
assert block.positions[0].range == [1.0, 2.0, 3.0, 4.0]
@REQUIRES_LIGHTRAG
def test_sidecar_unknown_content_is_preserved_or_rejected(tmp_path: Path) -> None:
bundle = tmp_path / "bundle"
bundle.mkdir()
blocks = bundle / "blocks.json"
manifest = {
"canonical_filename": "doc.pdf",
"parser": {"engine": "mineru", "parser_signature": "s"},
"blocks": {"path": "blocks.json"},
"assets": [],
}
blocks.write_text(json.dumps([{"type": "new_semantic", "text": "keep me"}]), encoding="utf-8")
assert "keep me" in sidecar.build_ir(manifest, bundle).blocks[0].content_template
blocks.write_text(json.dumps([{"type": "new_semantic"}]), encoding="utf-8")
with pytest.raises(sidecar.SidecarMappingError, match="no preservable text"):
sidecar.build_ir(manifest, bundle)
@REQUIRES_LIGHTRAG
def test_sidecar_asset_traversal_is_rejected(tmp_path: Path) -> None:
bundle = tmp_path / "bundle"
bundle.mkdir()
blocks = bundle / "blocks.json"
blocks.write_text(
json.dumps([{"type": "image", "img_path": "../outside.png"}]), encoding="utf-8"
)
manifest = {
"canonical_filename": "doc.pdf",
"parser": {},
"blocks": {"path": "blocks.json"},
"assets": [],
}
with pytest.raises(sidecar.SidecarMappingError, match="escapes"):
sidecar.build_ir(manifest, bundle)
@REQUIRES_LIGHTRAG
def test_official_legacy_mineru_golden_maps_without_private_builder(tmp_path: Path) -> None:
golden = FIXTURES / "mineru-legacy-official-example" / "content_list.json"
provenance = json.loads(
(golden.parent / "deeptutor-fixture-provenance.json").read_text(encoding="utf-8")
)
blocks = json.loads(golden.read_text(encoding="utf-8"))
# The official example's image bytes are not distributed with its docs;
# the authenticated current capture covers AssetSpec. The exact legacy
# table/equation/text records remain untouched here.
bridge_blocks = [block for block in blocks if block.get("type") != "image"]
source = tmp_path / "legacy.pdf"
source.write_bytes(b"legacy fixture source")
working = tmp_path / "version-1"
staged = ingress.freeze_document(
working,
source,
ParsedDocument(
markdown="# Legacy fixture",
blocks=bridge_blocks,
engine="mineru",
source_hash=provenance["content_sha256"],
parser_signature=provenance["commit"],
),
)
manifest, bundle = ingress.load_verified_bundle(working, staged.canonical_name)
document = sidecar.build_ir(manifest, bundle)
assert provenance["kind"] == "official-legacy-schema-example"
assert document.doc_title == "The response of flow duration curves to afforestation"
block = document.blocks[0]
assert block.tables[0].caption.startswith("Table 2")
assert "Q _ { \\% }" in block.equations[0].latex
assert {position.anchor for position in block.positions} == {"1", "3", "6"}
@REQUIRES_LIGHTRAG
def test_authenticated_current_mineru_golden_maps_from_public_artifacts(tmp_path: Path) -> None:
capture = FIXTURES / "mineru-v2-current"
provenance = json.loads(
(capture / "deeptutor-fixture-provenance.json").read_text(encoding="utf-8")
)
source = (capture / provenance["source"]["path"]).resolve()
assert provenance["capture_schema"] == 1
assert provenance["authenticated"] is True
assert provenance["service"] == "https://mineru.net/api/v4"
assert hashlib.sha256(source.read_bytes()).hexdigest() == provenance["source"]["sha256"]
for relative, expected_digest in provenance["artifacts"].items():
artifact = capture / relative
assert artifact.is_file()
assert hashlib.sha256(artifact.read_bytes()).hexdigest() == expected_digest
markdown, blocks, asset_dir = parsing_cache.load_ir(capture)
assert blocks is not None
assert asset_dir is not None
assert {block["type"] for block in blocks} == {"text", "equation", "table", "chart"}
staged = ingress.freeze_document(
tmp_path / "version-1",
source,
ParsedDocument(
markdown=markdown,
blocks=blocks,
asset_dir=asset_dir,
engine="mineru",
source_hash=provenance["source"]["sha256"],
parser_signature=provenance["model_version"],
),
)
manifest, bundle = ingress.load_verified_bundle(tmp_path / "version-1", staged.canonical_name)
document = sidecar.build_ir(manifest, bundle)
assert document.doc_title == "original"
assert document.blocks[0].heading == "DeepTutor LightRAG Bridge Fixture"
assert document.blocks[0].tables[0].caption == "Table 1. Retrieval engine paths"
assert "E = m c" in document.blocks[0].equations[0].latex
assert document.blocks[0].drawings[0].caption == "Figure 1. Synthetic trend chart."
assert len(document.assets) == 1
assert (
document.assets[0].source.read_bytes()
== (asset_dir / Path(blocks[-1]["img_path"]).name).read_bytes()
)
@@ -0,0 +1,196 @@
"""Offline integration smoke tests against the real pinned LightRAG SDK."""
from __future__ import annotations
import asyncio
from dataclasses import replace
from pathlib import Path
import numpy as np
import pytest
EmbeddingFunc = pytest.importorskip("lightrag.utils").EmbeddingFunc
from deeptutor.services.parsing.types import ParsedDocument
from deeptutor.services.rag.index_versioning import list_kb_versions
from deeptutor.services.rag.pipelines.lightrag import engine, ingress, storage
async def _fake_llm(_prompt, **_kwargs) -> str:
# This superset satisfies rc2's table/equation analysis schemas. Entity
# extraction may validly produce zero records; the document still reaches
# PROCESSED with real parser, chunk, storage and embedding code.
return '{"name":"fixture","description":"fixture analysis","equation":"x^2","type":"Other"}'
async def _fake_embedding(texts: list[str]) -> np.ndarray:
return np.ones((len(texts), 32), dtype=float)
def _configure_real_sdk(monkeypatch, llm=_fake_llm) -> None:
monkeypatch.setattr(engine, "build_llm_model_func", lambda **_kwargs: llm)
monkeypatch.setattr(
engine,
"build_embedding_func",
lambda **_kwargs: EmbeddingFunc(
embedding_dim=32,
max_token_size=4096,
func=_fake_embedding,
),
)
monkeypatch.setattr(
engine, "indexing_kwargs_from_settings", lambda: {"max_parallel_parse_native": 1}
)
monkeypatch.setattr(
engine, "constructor_kwargs_from_settings", lambda: {"entity_extract_max_gleaning": 0}
)
async def _process(working_dir: Path, staged: ingress.StagedDocument) -> dict:
rag = engine.build_rag(working_dir, enable_vlm=False)
await engine.initialize(rag)
failed = True
try:
track_id = await engine.enqueue(rag, [staged])
await rag.apipeline_process_enqueue_documents()
rows = await rag.aget_docs_by_track_id(track_id)
failed = False
return rows
finally:
await engine.finalize(rag, cancel_pending=failed)
def test_real_rc2_raw_bridge_reaches_processed(monkeypatch, tmp_path: Path) -> None:
_configure_real_sdk(monkeypatch)
working = tmp_path / "version-1"
working.mkdir()
source = tmp_path / "notes.md"
source.write_text("DeepTutor native LightRAG fixture.", encoding="utf-8")
staged = ingress.freeze_document(
working,
source,
ParsedDocument(
markdown="# Native fixture\n\nDeepTutor uses LightRAG.",
engine="text_only",
source_hash="fixture-source",
parser_signature="fixture-parser",
),
)
rows = asyncio.run(_process(working, staged))
assert len(rows) == 1
row = next(iter(rows.values()))
assert getattr(row.status, "value", row.status) == "processed"
assert row.file_path == "notes.md"
assert storage.has_output(working) is True
monkeypatch.setattr(
"deeptutor.services.rag.embedding_signature.embedding_meta_fields",
lambda: {"embedding": "fixture"},
)
storage.write_meta(working)
assert storage.meta_is_native_published(working) is True
assert list_kb_versions(tmp_path)[0]["ready"] is True
meta = storage._read_meta(working)
assert meta["parser_inputs"] == [{"engine": "text_only", "parser_signature": "fixture-parser"}]
def test_real_rc2_sidecar_bridge_reaches_processed(monkeypatch, tmp_path: Path) -> None:
_configure_real_sdk(monkeypatch)
working = tmp_path / "version-1"
working.mkdir()
source = tmp_path / "paper.pdf"
source.write_bytes(b"%PDF-1.4 fixture")
assets = tmp_path / "assets"
assets.mkdir()
(assets / "figure.png").write_bytes(b"fixture image")
staged = ingress.freeze_document(
working,
source,
ParsedDocument(
markdown="# Structured fixture",
blocks=[
{"type": "text", "text": "Structured fixture", "text_level": 1, "page_idx": 0},
{"type": "text", "text": "DeepTutor structured body.", "page_idx": 0},
{
"type": "table",
"table_body": "<table><tr><td>value</td></tr></table>",
"page_idx": 0,
},
{"type": "image", "img_path": "figure.png", "page_idx": 0},
{"type": "equation", "text": "x^2", "page_idx": 0},
],
asset_dir=assets,
engine="mineru",
source_hash="fixture-source",
parser_signature="fixture-parser",
),
)
# The image asset still passes through the real Sidecar writer; disabling
# i only avoids requiring a vision call in this deterministic offline test.
staged = replace(staged, process_options=staged.process_options.replace("i", ""))
rows = asyncio.run(_process(working, staged))
assert len(rows) == 1
row = next(iter(rows.values()))
assert getattr(row.status, "value", row.status) == "processed"
assert row.file_path == "paper.pdf"
assert storage.has_output(working) is True
assert list((ingress.pending_root(working) / "__parsed__").glob("paper.pdf"))
def test_real_rc2_append_uses_only_new_doc_and_links_existing_entity(
monkeypatch, tmp_path: Path
) -> None:
async def entity_llm(prompt, **_kwargs) -> str:
if "Second document" in prompt:
return (
"(entity<|#|>SECOND<|#|>CONCEPT<|#|>Second entity)\n"
"(relation<|#|>SHARED<|#|>SECOND<|#|>links<|#|>Shared links to Second)"
"<|COMPLETE|>"
)
return "(entity<|#|>SHARED<|#|>CONCEPT<|#|>Shared entity)<|COMPLETE|>"
_configure_real_sdk(monkeypatch, entity_llm)
working = tmp_path / "version-1"
working.mkdir()
first_source = tmp_path / "first.md"
second_source = tmp_path / "second.md"
first_source.write_text("First document names Shared.", encoding="utf-8")
second_source.write_text("Second document links Shared to Second.", encoding="utf-8")
first = ingress.freeze_document(
working,
first_source,
ParsedDocument(markdown="First document names Shared.", engine="text_only"),
)
async def run() -> None:
rag = engine.build_rag(working)
await engine.initialize(rag)
failed = True
try:
first_track = await engine.enqueue(rag, [first])
await rag.apipeline_process_enqueue_documents()
first_rows = await rag.aget_docs_by_track_id(first_track)
assert [row.file_path for row in first_rows.values()] == ["first.md"]
second = ingress.freeze_document(
working,
second_source,
ParsedDocument(
markdown="Second document links Shared to Second.", engine="text_only"
),
)
second_track = await engine.enqueue(rag, [second])
await rag.apipeline_process_enqueue_documents()
second_rows = await rag.aget_docs_by_track_id(second_track)
assert [row.file_path for row in second_rows.values()] == ["second.md"]
assert await rag.chunk_entity_relation_graph.get_node("SHARED") is not None
assert await rag.chunk_entity_relation_graph.get_node("SECOND") is not None
assert await rag.chunk_entity_relation_graph.get_edge("SHARED", "SECOND") is not None
failed = False
finally:
await engine.finalize(rag, cancel_pending=failed)
asyncio.run(run())
File diff suppressed because it is too large Load Diff
@@ -1,145 +1,66 @@
"""The LightRAG settings knobs must not break older RAG-Anything installs.
``max_concurrent_files`` rides on ``RAGAnythingConfig`` and
``llm_model_max_async`` / ``entity_extract_max_gleaning`` ride on RAG-Anything's
``lightrag_kwargs`` passthrough — a parameter that only exists from ~1.2.5,
while the supported range starts at 1.0.1. Passing it blind raised TypeError
and took the whole engine down, so the wiring asks the installed class first.
raganything is an optional extra and is absent from CI, so these tests exercise
``build_rag`` against stand-in classes with each constructor shape.
"""
"""Settings are wired directly to the pinned native LightRAG constructor."""
from __future__ import annotations
import importlib.util
from pathlib import Path
import sys
import types
from typing import Any
import pytest
from deeptutor.services.rag.pipelines.lightrag import engine as engine_module
from deeptutor.services.rag.pipelines.lightrag import engine
pytestmark = pytest.mark.skipif(
importlib.util.find_spec("lightrag") is None,
reason="requires the optional rag-lightrag extra",
)
class _ModernConfig:
"""RAG-Anything >= 1.2.5: config takes the batch knob."""
def __init__(self, working_dir: str, max_concurrent_files: int = 1) -> None:
self.working_dir = working_dir
self.max_concurrent_files = max_concurrent_files
class _NativeLightRag:
def __init__(self, **kwargs) -> None:
self.kwargs = kwargs
class _LegacyConfig:
"""RAG-Anything 1.0.x: no batch knob at all."""
def __init__(self, working_dir: str) -> None:
self.working_dir = working_dir
def _stub_build(monkeypatch) -> None:
monkeypatch.setattr(engine, "_require_exact_version", lambda: None)
monkeypatch.setattr(engine, "_register_parser", lambda: None)
monkeypatch.setattr(engine, "_controlled_class", lambda: _NativeLightRag)
monkeypatch.setattr(engine, "build_llm_model_func", lambda **_kwargs: "llm")
monkeypatch.setattr(engine, "build_embedding_func", lambda **_kwargs: "embedding")
class _ModernRag:
"""RAG-Anything >= 1.2.5: exposes the lightrag_kwargs passthrough."""
def __init__(
self,
config: Any,
llm_model_func: Any,
vision_model_func: Any,
embedding_func: Any,
lightrag_kwargs: dict[str, Any] | None = None,
) -> None:
self.config = config
self.lightrag_kwargs = lightrag_kwargs
self.set_content_source_func = None
class _LegacyRag:
"""RAG-Anything 1.0.x: no passthrough."""
def __init__(
self,
config: Any,
llm_model_func: Any,
vision_model_func: Any,
embedding_func: Any,
) -> None:
self.config = config
self.lightrag_kwargs = None
self.set_content_source_func = None
@pytest.fixture
def fake_raganything(monkeypatch: pytest.MonkeyPatch):
"""Install a stand-in ``raganything`` module with the given class shapes."""
def install(rag_cls: type, config_cls: type) -> None:
module = types.ModuleType("raganything")
module.RAGAnything = rag_cls # type: ignore[attr-defined]
module.RAGAnythingConfig = config_cls # type: ignore[attr-defined]
monkeypatch.setitem(sys.modules, "raganything", module)
return install
@pytest.fixture(autouse=True)
def _stub_adapters(monkeypatch: pytest.MonkeyPatch) -> None:
for name in ("build_llm_model_func", "build_vision_model_func", "build_embedding_func"):
monkeypatch.setattr(engine_module, name, lambda **_kwargs: lambda *a, **k: None)
@pytest.fixture(autouse=True)
def _settings(monkeypatch: pytest.MonkeyPatch) -> None:
def test_native_constructor_receives_every_supported_knob(monkeypatch, tmp_path: Path) -> None:
_stub_build(monkeypatch)
monkeypatch.setattr(
engine_module, "indexing_kwargs_from_settings", lambda: {"max_concurrent_files": 4}
engine, "indexing_kwargs_from_settings", lambda: {"max_parallel_parse_native": 4}
)
monkeypatch.setattr(
engine_module,
"lightrag_kwargs_from_settings",
engine,
"constructor_kwargs_from_settings",
lambda: {"llm_model_max_async": 8, "entity_extract_max_gleaning": 2},
)
rag = engine.build_rag(tmp_path)
def test_modern_raganything_receives_every_knob(fake_raganything, tmp_path: Path) -> None:
fake_raganything(_ModernRag, _ModernConfig)
rag = engine_module.build_rag(tmp_path)
assert rag.config.max_concurrent_files == 4
assert rag.lightrag_kwargs == {"llm_model_max_async": 8, "entity_extract_max_gleaning": 2}
assert rag.kwargs["working_dir"] == str(tmp_path)
assert rag.kwargs["workspace"] == engine.workspace_for(tmp_path)
assert rag.kwargs["llm_model_func"] == "llm"
assert rag.kwargs["embedding_func"] == "embedding"
assert rag.kwargs["auto_manage_storages_states"] is False
assert rag.kwargs["max_parallel_parse_native"] == 4
assert rag.kwargs["llm_model_max_async"] == 8
assert rag.kwargs["entity_extract_max_gleaning"] == 2
assert rag.kwargs["vlm_process_enable"] is False
assert "role_llm_configs" not in rag.kwargs
def test_legacy_raganything_still_builds(
fake_raganything, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""The knobs are dropped with a warning rather than raising TypeError."""
fake_raganything(_LegacyRag, _LegacyConfig)
def test_vlm_role_is_only_configured_when_enabled(monkeypatch, tmp_path: Path) -> None:
_stub_build(monkeypatch)
monkeypatch.setattr(engine, "build_vision_model_func", lambda **_kwargs: "vision")
monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)
monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)
with caplog.at_level("WARNING"):
rag = engine_module.build_rag(tmp_path)
rag = engine.build_rag(tmp_path, enable_vlm=True)
assert rag.lightrag_kwargs is None
assert not hasattr(rag.config, "max_concurrent_files")
assert "max_concurrent_files" in caplog.text
assert "lightrag_kwargs" in caplog.text
def test_mixed_versions_drop_only_the_unsupported_knob(fake_raganything, tmp_path: Path) -> None:
fake_raganything(_LegacyRag, _ModernConfig)
rag = engine_module.build_rag(tmp_path)
assert rag.config.max_concurrent_files == 4
assert rag.lightrag_kwargs is None
def test_no_configured_knobs_passes_nothing_extra(
fake_raganything, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(engine_module, "indexing_kwargs_from_settings", dict)
monkeypatch.setattr(engine_module, "lightrag_kwargs_from_settings", dict)
fake_raganything(_ModernRag, _ModernConfig)
rag = engine_module.build_rag(tmp_path)
assert rag.config.max_concurrent_files == 1 # the library default
assert rag.lightrag_kwargs is None
role = rag.kwargs["role_llm_configs"]["vlm"]
assert role.func == "vision"
assert rag.kwargs["vlm_process_enable"] is True
@@ -134,6 +134,75 @@ def test_loader_skips_document_when_active_engine_cannot_parse(
assert "Settings" in caplog.text
def test_loader_explains_scanned_pdf_when_parser_yields_images_only(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
pytest.importorskip("llama_index.core")
from deeptutor.services.parsing.types import ParsedDocument
from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module
from deeptutor.services.rag.pipelines.llamaindex.document_loader import (
LlamaIndexDocumentLoader,
)
pdf_path = tmp_path / "scan.pdf"
pdf_path.write_bytes(b"stub")
asset_dir = tmp_path / "assets"
asset_dir.mkdir()
(asset_dir / "page-1.png").write_bytes(b"\x89PNG\r\n")
_install_stub_parse_service(
monkeypatch,
{
"scan.pdf": ParsedDocument(
markdown="",
engine="pymupdf4llm",
asset_dir=asset_dir,
)
},
)
class _TextOnlyClient:
config = type("Config", (), {"binding": "openai", "model": "text-embedding"})()
def supports_multimodal_contents(self) -> bool:
return False
monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _TextOnlyClient())
with caplog.at_level("WARNING"):
documents = asyncio.run(LlamaIndexDocumentLoader().load([str(pdf_path)]))
assert documents == []
assert "pymupdf4llm engine extracted 1 image(s) but no text" in caplog.text
assert "scanned PDF" in caplog.text
assert "OCR-capable" in caplog.text
assert "Settings, Document Parsing" in caplog.text
def test_loader_keeps_generic_empty_warning_for_non_pdf(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
pytest.importorskip("llama_index.core")
from deeptutor.services.parsing.types import ParsedDocument
from deeptutor.services.rag.pipelines.llamaindex.document_loader import (
LlamaIndexDocumentLoader,
)
docx_path = tmp_path / "blank.docx"
docx_path.write_bytes(b"stub")
_install_stub_parse_service(
monkeypatch,
{"blank.docx": ParsedDocument(markdown="", engine="markitdown")},
)
with caplog.at_level("WARNING"):
documents = asyncio.run(LlamaIndexDocumentLoader().load([str(docx_path)]))
assert documents == []
assert caplog.text.count("Skipped empty document: blank.docx") == 1
assert "scanned PDF" not in caplog.text
def test_loader_indexes_images_extracted_from_parsed_document(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
+62 -6
View File
@@ -23,6 +23,7 @@ from deeptutor.services.skill.hub import (
get_hub_provider,
install_from_hub,
parse_hub_ref,
split_owner_slug,
)
from deeptutor.services.skill.service import (
SkillExistsError,
@@ -176,6 +177,13 @@ def test_origin_recorded_and_dropped_on_delete(tmp_path: Path, svc: SkillService
def test_parse_hub_ref_forms() -> None:
assert parse_hub_ref("clawhub:my-skill") == ("clawhub", "my-skill", None)
assert parse_hub_ref("clawhub:acme/my-skill@1.2.0") == (
"clawhub",
"acme/my-skill",
"1.2.0",
)
assert split_owner_slug("acme/my-skill") == ("acme", "my-skill")
assert split_owner_slug("my-skill") == ("", "my-skill")
# No prefix resolves to the built-in default hub (EduHub).
assert parse_hub_ref("my-skill") == ("eduhub", "my-skill", None)
assert parse_hub_ref("eduhub:my-skill") == ("eduhub", "my-skill", None)
@@ -214,9 +222,16 @@ def test_extract_skill_zip_preserves_dirs_and_blocks_traversal(tmp_path: Path) -
# ── ClawHubProvider over MockTransport ───────────────────────────────────
def _clawhub_client(zip_payload: bytes, *, ok: bool = True) -> httpx.Client:
def _clawhub_client(
zip_payload: bytes,
*,
ok: bool = True,
requests: list[tuple[str, dict[str, str]]] | None = None,
) -> httpx.Client:
def handler(request: httpx.Request) -> httpx.Response:
path = request.url.path
if requests is not None:
requests.append((path, dict(request.url.params)))
if path == "/api/v1/search":
return httpx.Response(
200,
@@ -224,6 +239,7 @@ def _clawhub_client(zip_payload: bytes, *, ok: bool = True) -> httpx.Client:
"results": [
{
"slug": "demo",
"ownerHandle": "acme",
"displayName": "Demo",
"summary": "demo summary",
"version": "1.2.0",
@@ -245,20 +261,31 @@ def _clawhub_client(zip_payload: bytes, *, ok: bool = True) -> httpx.Client:
def test_clawhub_search_verify_fetch(tmp_path: Path) -> None:
payload = _zip_bytes({"demo/SKILL.md": "---\nname: demo\ndescription: d\n---\n\nbody\n"})
provider = ClawHubProvider(client=_clawhub_client(payload))
calls: list[tuple[str, dict[str, str]]] = []
provider = ClawHubProvider(client=_clawhub_client(payload, requests=calls))
refs = provider.search("demo")
assert refs[0].slug == "demo" and refs[0].version == "1.2.0"
assert refs[0].slug == "demo"
assert refs[0].owner_handle == "acme"
assert refs[0].version == "1.2.0"
assert provider.verify("demo").status == "ok"
assert provider.verify("acme/demo").status == "ok"
fetched = provider.fetch("demo")
fetched = provider.fetch("acme/demo")
try:
assert (fetched.root / "SKILL.md").is_file() # wrapper dir unwrapped
assert fetched.ref.version == "1.2.0" # resolved from skill detail
assert fetched.ref.slug == "demo"
assert fetched.ref.owner_handle == "acme"
finally:
fetched.cleanup()
assert not fetched.cleanup_dir.exists()
assert ("ownerHandle", "acme") in calls[1][1].items()
assert calls[2] == (
"/api/v1/download",
{"slug": "demo", "tag": "latest", "ownerHandle": "acme"},
)
assert calls[3] == ("/api/v1/skills/demo", {"ownerHandle": "acme"})
def test_clawhub_verify_states() -> None:
@@ -370,20 +397,31 @@ class _FakeProvider:
self._pkg = pkg
self._verdict = verdict
self.last_cleanup: Path | None = None
self.last_verify: str | None = None
self.last_fetch: str | None = None
def search(self, query: str, *, limit: int = 10) -> list[HubSkillRef]:
return []
def verify(self, slug: str, *, version: str | None = None) -> HubVerdict:
self.last_verify = slug
return self._verdict
def fetch(self, slug: str, *, version: str | None = None) -> FetchedSkill:
self.last_fetch = slug
owner_handle, skill_slug = split_owner_slug(slug)
tmp = Path(tempfile.mkdtemp(prefix="fakehub-"))
root = tmp / "pkg"
shutil.copytree(self._pkg, root)
self.last_cleanup = tmp
return FetchedSkill(
ref=HubSkillRef(hub=self.name, slug=slug, summary="registry summary", version="0.9.0"),
ref=HubSkillRef(
hub=self.name,
slug=skill_slug,
owner_handle=owner_handle,
summary="registry summary",
version="0.9.0",
),
root=root,
cleanup_dir=tmp,
)
@@ -401,10 +439,28 @@ def test_install_from_hub_happy_path(tmp_path: Path, svc: SkillService) -> None:
"0.9.0",
"ok",
)
assert origin["slug"] == "demo"
assert "owner_handle" not in origin
assert origin["installed_at"]
assert provider.last_cleanup is not None and not provider.last_cleanup.exists()
def test_install_from_hub_records_publisher_scope(tmp_path: Path, svc: SkillService) -> None:
pkg = _make_package(tmp_path / "pkg", frontmatter="name: demo\ndescription: d")
provider = _FakeProvider(pkg, HubVerdict(status="ok"))
outcome = install_from_hub("fakehub:acme/demo", service=svc, provider=provider)
assert provider.last_verify == "acme/demo"
assert provider.last_fetch == "acme/demo"
assert outcome.ref.slug == "demo"
assert outcome.ref.owner_handle == "acme"
origin = svc.hub_origin("demo")
assert origin is not None
assert origin["slug"] == "demo"
assert origin["owner_handle"] == "acme"
def test_install_from_hub_blocks_suspicious_unless_overridden(
tmp_path: Path, svc: SkillService
) -> None:
+12 -1
View File
@@ -82,13 +82,24 @@ def test_pageindex_sdk_range_matches_every_install_surface() -> None:
).splitlines().count(expected) == 1
def test_lightrag_extra_is_the_exact_native_sdk_without_parser_transitives() -> None:
with (REPOSITORY_ROOT / "pyproject.toml").open("rb") as file:
extras = tomllib.load(file)["project"]["optional-dependencies"]
requirements = extras["rag-lightrag"]
assert requirements == ["lightrag-hku==1.5.7rc2"]
names = [requirement.lower().split("=", 1)[0].split("<", 1)[0] for requirement in requirements]
assert "raganything" not in names
assert "mineru" not in names
@pytest.mark.parametrize(
"expected",
[
"loguru>=0.7.3,<1.0.0",
"json-repair>=0.57.0,<1.0.0",
"pyte>=0.8.1",
"pdfplumber>=0.11.0,<0.11.8",
"pdfplumber>=0.11.0",
"reportlab>=4.0.0",
],
)
+13
View File
@@ -344,3 +344,16 @@ def test_to_dict_legacy_path_also_emits_v3() -> None:
{"label": "a", "description": None},
{"label": "b", "description": None},
]
def test_prompt_decodes_dense_unicode_escapes() -> None:
"""Regression for #973: model tool args can carry literal \\uXXXX stems."""
escaped = "\\u300c\\u6570\\u5236\\u8f6c\\u6362\\u300d"
payload, err = build_ask_user_payload(
questions=[{"prompt": escaped, "options": ["A", "B"]}],
intro=escaped,
)
assert err is None
assert payload is not None
assert payload.intro == "「数制转换」"
assert payload.questions[0].prompt == "「数制转换」"
@@ -0,0 +1,74 @@
from __future__ import annotations
from pathlib import Path
import yaml
from deeptutor.tools.builtin import CodeExecutionTool
from deeptutor.tools.prompting import load_prompt_hints
def test_code_execution_schema_and_hints_cover_file_generation() -> None:
definition = CodeExecutionTool().get_definition()
hint = load_prompt_hints("code_execution", language="en")
exec_hint = load_prompt_hints("exec", language="en")
assert "files generated" in definition.description
assert "code-generated deliverables" in definition.description
assert "creating a file" in hint.when_to_use
assert "python -c" in hint.guideline
assert "heredoc" in hint.guideline
assert "code_execution" in exec_hint.guideline
def test_code_execution_guidance_is_bilingual() -> None:
for language in ("en", "zh"):
hint = load_prompt_hints("code_execution", language=language)
exec_hint = load_prompt_hints("exec", language=language)
assert "Python" in hint.when_to_use
assert "python -c" in hint.guideline
assert "heredoc" in hint.guideline
assert "code_execution" in exec_hint.guideline
assert "python -c" in exec_hint.guideline
assert "heredoc" in exec_hint.guideline
def test_chat_prompts_prefer_code_execution_for_python_files() -> None:
root = Path(__file__).parents[2] / "deeptutor" / "agents" / "chat" / "prompts"
missing_artifact_warnings = {
"en": "without that list, do not claim a file was created",
"zh": "没有这个清单就不要宣称已创建文件",
}
for language in ("en", "zh"):
data = yaml.safe_load((root / language / "agentic_chat.yaml").read_text())
prompt = data["loop"]["system"]
assert "code_execution" in prompt
assert "python -c" in prompt
assert "heredoc" in prompt
assert missing_artifact_warnings[language] in prompt
def test_solve_prompts_route_python_files_to_code_execution() -> None:
root = Path(__file__).parents[2] / "deeptutor" / "capabilities" / "solve" / "prompts"
shell_only_guidance = {
"en": "`exec` only for genuinely shell-only commands",
"zh": "`exec` 只用于真正必须使用 shell 的命令",
}
for language in ("en", "zh"):
prompt = (root / language / "system.md").read_text()
assert "code_execution" in prompt
assert "Python-generated files" in prompt or "用 Python 生成文件" in prompt
assert shell_only_guidance[language] in prompt
def test_office_skills_use_code_execution_for_python_deliverables() -> None:
root = Path(__file__).parents[2] / "deeptutor" / "skills" / "builtin"
for skill in ("docx", "pdf", "pptx", "xlsx"):
document = (root / skill / "SKILL.md").read_text()
assert "code_execution" in document
assert "python -c" in document
assert "heredoc" in document

Some files were not shown because too many files have changed in this diff Show More