Merge #2379 from remote-controlled-man

This commit is contained in:
Bingxi Zhao (Frank)
2026-11-06 01:56:25 +08:00
5 changed files with 98 additions and 9 deletions

View File

@@ -25,6 +25,12 @@ _FIGURE = re.compile(r"(?:fig(?:ure)?\.?|图|圖|table|表)\s*([0-9]+(?:[.\-][0-
_PAGE = re.compile(r"(?:page|p\.|第)\s*(\d+)\s*(?:页|頁)?", re.I)
def page_reference(text: str) -> int | None:
"""Return the first page reference recognized by visual inspection."""
match = _PAGE.search(text)
return int(match.group(1)) if match else None
def figure_labels(text: str) -> list[str]:
return list(dict.fromkeys(m.group(1).casefold() for m in _FIGURE.finditer(text)))
@@ -232,8 +238,7 @@ def retrieve_visual(
error="multiple_references",
)
label = labels[0] if labels else ""
match = _PAGE.search(query)
page = int(match.group(1)) if match else None
page = page_reference(query)
candidates = [
r
for key, r in records.items()

View File

@@ -185,7 +185,7 @@ class RAGTool(_PromptHintsMixin, BaseTool):
type="string",
required=False,
nullable=True,
description="Exact document path from kb_files for visual/page inspection; prevents substitution across sources.",
description="Exact document path from kb_files for visual/page inspection with a page, figure, region or asset_id. Source-only scoped text retrieval is unsupported; it never falls back to a whole-KB search.",
),
ToolParameter(
name="asset_id",
@@ -301,15 +301,24 @@ class RAGTool(_PromptHintsMixin, BaseTool):
raise ValueError("RAG requires an explicit kb_name.")
event_sink = None if kwargs.get("_mastery_source_context") else kwargs.get("event_sink")
vision_supported = bool(kwargs.get("_vision_supported", False))
from deeptutor.services.rag.source_visuals import figure_labels, retrieve_visual
from deeptutor.services.rag.source_visuals import (
figure_labels,
page_reference,
retrieve_visual,
)
exact_keys = ("source_path", "asset_id", "figure", "page", "region", "source_hash")
selectors = _normalize_rag_selectors(kwargs)
if isinstance(selectors, str):
return _rag_selector_error(selectors)
if any(
selectors.get(key) is not None and selectors.get(key) != "" for key in exact_keys
) or figure_labels(query):
visual_requested = any(
selectors.get(key) is not None and selectors.get(key) != ""
for key in ("asset_id", "figure", "page", "region")
) or bool(figure_labels(query))
if (
any(selectors.get(key) is not None and selectors.get(key) != "" for key in exact_keys)
or visual_requested
):
from deeptutor.multi_user.knowledge_access import resolve_for_rag
from deeptutor.services.rag.kb_paths import resolve_kb_dir
@@ -318,6 +327,20 @@ class RAGTool(_PromptHintsMixin, BaseTool):
return ToolResult(
content=f"Knowledge base '{kb_name}' is not accessible.", success=False
)
if (
selectors.get("source_path")
and not visual_requested
and page_reference(query) is None
):
return ToolResult(
content=(
"RAG does not support scoped text retrieval by source_path. "
"No search was run. For exact visual inspection, also select "
"a page, figure, region or asset_id."
),
success=False,
metadata={"error_type": "source_scope_unsupported"},
)
try:
evidence = await asyncio.to_thread(
retrieve_visual,

View File

@@ -2,5 +2,5 @@ short_description: "Retrieve relevant passages from one of the attached knowledg
when_to_use: "Use when the answer is likely covered by the attached knowledge bases — definitions, formulas, concepts, or textbook explanations."
input_format: "{\"query\": \"non-empty natural-language query\", \"kb_name\": \"one of the attached knowledge base names\"}."
guideline: "Prefer RAG before external search for course material. For concept discovery, query in the source language too when needed. For an exact figure, use figure plus source_path from kb_files; for a vector diagram, sparse caption, table or unreadable labels use source_path/page and optionally region=[x0,y0,x1,y1] normalized to 0..1. Reuse asset_id or source_hash from a citation for follow-ups; retrieve actual pixels again before detailed visual claims. Compare two sources with separate bounded calls."
note: "The query must be non-empty. Keep figure/table numbers and source boundaries exact. Ambiguity, missing pixels, unsupported pages or conflicting evidence require source selection, page inspection or abstention; never substitute a related figure. Distinguish visible observations, caption-only interpretation and general background. A citation and original image must support each source-specific claim."
note: "The query must be non-empty. Keep figure/table numbers and source boundaries exact. Ambiguity, missing pixels, unsupported pages or conflicting evidence require source selection, page inspection or abstention; never substitute a related figure. Distinguish visible observations, caption-only interpretation and general background. A citation and original image must support each source-specific claim. source_path alone does not enable document-scoped text retrieval and returns source_scope_unsupported; do not drop a required source scope to retry against the whole knowledge base."
phase: "exploration"

View File

@@ -2,5 +2,5 @@ short_description: "在用户挂载的某个知识库中检索相关内容。"
when_to_use: "当答案大概率来自用户挂载的知识库(定义、公式、概念解释、教材内容)时使用。"
input_format: "{\"query\": \"非空自然语言查询\", \"kb_name\": \"挂载的某个知识库名称\"}。"
guideline: "课程材料优先检索知识库;概念检索必要时也用来源语言查询。精确图号用 figure 和 kb_files 中的 source_path;矢量图、稀疏图注、表格或模糊标签用 source_path/page,必要时用归一化区域 region=[x0,y0,x1,y1]。追问沿用引用的 asset_id 或 source_hash,并重新读取实际像素后再作详细视觉判断。比较两份材料时分别调用,保持图片预算有界。"
note: "query 不能为空。保持图表编号和来源边界准确;歧义、缺失像素、不支持的页面或冲突证据应要求选择来源、检查页面或明确保留判断,不能替换成相似图。区分可见观察、仅基于图注的解释和一般背景知识;来源特定结论必须展示可核对的原图与位置。"
note: "query 不能为空。保持图表编号和来源边界准确;歧义、缺失像素、不支持的页面或冲突证据应要求选择来源、检查页面或明确保留判断,不能替换成相似图。区分可见观察、仅基于图注的解释和一般背景知识;来源特定结论必须展示可核对的原图与位置。 单独传入 source_path 不支持限定文档的文本检索,会返回 source_scope_unsupported;不要为了重试而删除必须保留的来源范围、改查整个知识库。"
phase: "exploration"

View File

@@ -157,3 +157,64 @@ async def test_malformed_selectors_fail_visibly_without_substitution(
assert result.metadata["error_type"] == "invalid_selector"
assert rag_calls["rag_search"] == []
assert rag_calls["resolve_for_rag"] == []
@pytest.mark.parametrize(
"extra",
[
{},
{"region": [], "page": None, "asset_id": None, "figure": None},
{"source_hash": "a" * 64, "_vision_supported": True},
],
)
@pytest.mark.asyncio
async def test_source_only_text_query_reports_unsupported_scope(kb, rag_calls, extra):
(kb / "raw" / "notes.txt").write_text("Keep this source private.", encoding="utf-8")
result = await RAGTool().execute(
query="What does this document say?",
kb_name=kb.name,
source_path="notes.txt",
**extra,
)
assert not result.success
assert result.metadata["error_type"] == "source_scope_unsupported"
assert "scoped text retrieval" in result.content
assert result.sources == []
assert result.model_message is None
assert rag_calls["rag_search"] == []
assert rag_calls["resolve_for_rag"] == [kb.name]
@pytest.mark.asyncio
async def test_source_only_scope_keeps_knowledge_base_access_check(kb, rag_calls, monkeypatch):
monkeypatch.setattr("deeptutor.multi_user.knowledge_access.resolve_for_rag", lambda _name: None)
result = await RAGTool().execute(
query="What does this document say?",
kb_name=kb.name,
source_path="notes.txt",
)
assert not result.success
assert "not accessible" in result.content
assert result.sources == []
assert rag_calls["rag_search"] == []
@pytest.mark.parametrize("query", ["Inspect page 1", "检查第1页", "Inspect p. 1"])
@pytest.mark.asyncio
async def test_source_with_query_page_keeps_visual_inspection(kb, rag_calls, query):
result = await RAGTool().execute(
query=query,
kb_name=kb.name,
source_path="manual.pdf",
_vision_supported=True,
)
assert result.success
assert result.metadata["evidence_kind"] == "exact_source_visual"
assert result.model_message["content"][1]["type"] == "image_url"
assert "pump seal" in result.content
assert rag_calls["rag_search"] == []
unscoped = await RAGTool().execute(query=query, kb_name=kb.name)
assert unscoped.success
assert unscoped.content == "semantic answer"
assert len(rag_calls["rag_search"]) == 1