RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
Refactor: the tool usage in agent search progress (#17490)
Kevin Hu06562cb03d6e
diff --git a/rag/advanced_rag/harness/agent.py b/rag/advanced_rag/harness/agent.pyindex 6c154b723a..1fe2223b5a 100644--- a/rag/advanced_rag/harness/agent.py+++ b/rag/advanced_rag/harness/agent.py@@ -32,6 +32,11 @@ from rag.advanced_rag.harness.prompts.research_agent_prompt import (_LOG = logging.getLogger(__name__)+# Navigation tools that return passages (evidence chunks). After one of these+# runs, we judge sufficiency before the agent broadens into a full search.+_NAV_CHUNK_TOOLS = {"ontology_navigate", "mindmap_navigate"}++class ResearchToolSession:"""ToolCallSession adapter routing native tool calls to the harness pipeline.@@ -41,9 +46,10 @@ class ResearchToolSession:return its structured arguments as the claim result."""- def __init__(self, pipeline: Pipeline, phase: str):+ def __init__(self, pipeline: Pipeline, phase: str, claim: ClaimTarget | None = None):self.pipeline = pipelineself.phase = phase+ self.claim = claimself.report: dict | None = Noneself.got_evidence = Falseself.evidence_ids: list[int] = []@@ -60,7 +66,33 @@ class ResearchToolSession:if result.chunks:self.got_evidence = Trueself._record_evidence_ids(result.chunks)- return _fmt_tool_result(result)+ message = _fmt_tool_result(result)+ # Post-navigation sufficiency gate: once a navigation tool has returned+ # passages, decide whether they already answer the task and, if so, steer+ # the agent to finalize instead of running a broader (noisier) search.+ if name in _NAV_CHUNK_TOOLS and result.chunks and self.claim is not None:+ if await self._navigation_sufficient(result.chunks):+ ev = ", ".join(str(i) for i in self.evidence_ids) or "the passages above"+ message += f"\n\n[sufficiency check] These passages appear to answer the task. Call generate_report now with evidence_ids=[{ev}] — do not run further searches."+ return message++ async def _navigation_sufficient(self, chunks: list[dict]) -> bool:+ """One-shot LLM judge: do the given passages already answer the claim?"""+ try:+ passages = "\n\n".join((c.get("content_with_weight") or c.get("text") or "")[:500] for c in chunks[:8])+ if not passages.strip():+ return False+ system = "Judge whether the passages already contain enough information to answer the task. Reply with a single word: YES or NO."+ user = f"Task:\n{self.claim.description}\n\nPassages:\n{passages}\n\nAnswer (YES or NO):"+ ans = await self.pipeline.tools.chat_mdl.async_chat(system, [{"role": "user", "content": user}], {"temperature": 0.0})+ if isinstance(ans, tuple):+ ans = ans[0]+ ans = re.sub(r"^.*</think>", "", ans or "", flags=re.DOTALL)+ _LOG.exception("[Navigation] sufficiency check: %s", ans)+ return ans.strip().lower().startswith("yes")+ except Exception:+ _LOG.exception("[Navigation] sufficiency check failed")+ return Falsedef _normalize_report(self, report: dict) -> dict:normalized = dict(report)@@ -123,6 +155,7 @@ async def research_agent_loop(available_tools=mode.available_tools,compilation_map=compilation_map,context=context,+ has_routed_scope=bool(getattr(pipeline, "_routed_docs", None)),)# Deep-copy so binding tools never leaks onto the shared chat model.@@ -145,7 +178,7 @@ async def _research_native() -> dict:"""Bind tools onto ``agent_mdl`` and let its native tool loop drive research."""schemas = _build_tool_schemas(gated_defs)- session = ResearchToolSession(pipeline, phase)+ session = ResearchToolSession(pipeline, phase, claim)agent_mdl.bind_tools(session, schemas)# Bound the model's internal tool loop to the mode's agent-cycle budget.if hasattr(agent_mdl, "mdl") and hasattr(agent_mdl.mdl, "max_rounds"):@@ -339,7 +372,7 @@ def _fmt_tool_result(result: ToolResult) -> str:if result.error:return f"[tool error] {result.error}"parts: list[str] = []- # Some tools (catalog_navigate, structured_query) answer directly rather than+ # Some tools (ontology_navigate, structured_query) answer directly rather than# only returning passages — surface that, or the agent never sees it.answer = (result.metadata or {}).get("answer") if isinstance(result.metadata, dict) else ""if answer:diff --git a/rag/advanced_rag/harness/config.py b/rag/advanced_rag/harness/config.pyindex 0c996d6469..b618495248 100644--- a/rag/advanced_rag/harness/config.py+++ b/rag/advanced_rag/harness/config.py@@ -52,8 +52,8 @@ THINKING_MODES: dict[str, ExecutionStrategy] = {available_tools=["hybrid_search","web_search",- "catalog_navigate",- "dataset_navigate",+ "ontology_navigate",+ "dataset_navigation_by_tree","graph_explore","inspector_open_context","inspector_compare",@@ -79,8 +79,8 @@ THINKING_MODES: dict[str, ExecutionStrategy] = {"bm25_search","web_search","structured_query",- "catalog_navigate",- "dataset_navigate",+ "ontology_navigate",+ "dataset_navigation_by_tree","mindmap_navigate","graph_explore","wiki_query",diff --git a/rag/advanced_rag/harness/pipeline.py b/rag/advanced_rag/harness/pipeline.pyindex 408bd05043..a8ae567528 100644--- a/rag/advanced_rag/harness/pipeline.py+++ b/rag/advanced_rag/harness/pipeline.py@@ -9,6 +9,12 @@ from rag.advanced_rag.harness.tools.registry import TOOL_REGISTRY_LOG = logging.getLogger(__name__)+# Tools that retrieve *within* a set of documents. When a routing tool+# (``dataset_navigation_by_tree``) has produced a relevant-document set, these+# inherit it as their ``doc_scope`` unless the caller passed one explicitly, so+# a follow-up search stays within the routed docs instead of re-scanning the KB.+_DOC_SCOPE_CONSUMERS = {"ontology_navigate", "mindmap_navigate", "graph_explore", "hybrid_search"}+class Pipeline:"""Unified tool execution layer.@@ -23,6 +29,8 @@ class Pipeline:self.tools = rag_toolsself.compilation_map = compilation_map or {}self.trace: list[dict] = []+ # Latest relevant-document set produced by a routing tool this run.+ self._routed_docs: list[str] = []async def execute(self, tool_name: str, **kwargs) -> ToolResult:"""Execute a registered tool by name."""@@ -34,12 +42,23 @@ class Pipeline:if not fn:return ToolResult(chunks=[], metadata={}, error=f"Tool {tool_name} has no executor")+ # Downstream scoping: a within-document tool inherits the doc IDs a prior+ # router (dataset_navigation_by_tree) produced, unless the caller passed+ # an explicit doc_scope.+ if tool_name in _DOC_SCOPE_CONSUMERS and self._routed_docs and not kwargs.get("doc_scope"):+ kwargs["doc_scope"] = list(self._routed_docs)+start = time.time()try:raw = await fn(self.tools, **kwargs)elapsed = time.time() - startself.trace.append({"tool": tool_name, "args": kwargs, "elapsed": elapsed, "success": True})result = self._normalize(raw)+ # A routing tool (e.g. dataset_navigation_by_tree) yields the relevant+ # document IDs; remember them so the scope-consuming tools above can+ # inherit them on later turns.+ if result.docs:+ self._routed_docs = list(result.docs)# Feed the shared citation pool: agent searches go through the# pipeline, so without this their evidence never reaches kbinfos and# the final answer has nothing to cite.@@ -103,9 +122,14 @@ class Pipeline:if isinstance(raw, dict):return ToolResult(chunks=raw.get("chunks", []),+ docs=raw.get("docs") or None,metadata={"aggs": raw.get("doc_aggs", []), "answer": raw.get("answer", "")},)if isinstance(raw, list):+ # A list of doc-id strings is a document-routing result (e.g.+ # dataset_navigation_by_tree); a list of dicts is chunks.+ if raw and all(isinstance(x, str) for x in raw):+ return ToolResult(docs=list(raw), metadata={})return ToolResult(chunks=raw, metadata={})return ToolResult(chunks=[], metadata={"raw": str(raw)})diff --git a/rag/advanced_rag/harness/prompts/research_agent_prompt.py b/rag/advanced_rag/harness/prompts/research_agent_prompt.pyindex 92d3cb84d4..67bec12038 100644--- a/rag/advanced_rag/harness/prompts/research_agent_prompt.py+++ b/rag/advanced_rag/harness/prompts/research_agent_prompt.py@@ -16,9 +16,14 @@ Current phase: {phase}Phase hint: {phase_hint}Rules:-1. Prefer search / navigation tools to gather evidence for the task.-2. Use think_tool to analyze results and plan the next step after each search.-3. When you have gathered enough evidence, call generate_report with your findings+1. Go coarse-to-fine. First narrow the corpus with navigation tools (dataset_navigation_by_tree,+ then ontology_navigate / mindmap_navigate).+2. After a navigation tool returns passages, judge whether they already answer the task.+ If they do, call generate_report immediately — do NOT search further.+3. Only call hybrid_search (or other broad search tools) when navigation did not yield+ sufficient evidence.+4. Use think_tool to analyze results and plan the next step.+5. When you have gathered enough evidence, call generate_report with your findings(report, is_verified, confidence, evidence_ids, gaps, discovered_claims).You have at most {max_cycles} tool-calling rounds. Call exactly one tool per round,@@ -37,9 +42,12 @@ Available tools:{tool_list}Rules:-1. Prefer search tools to gather information.-2. Use think_tool to analyze results after each search.-3. When you are confident enough to answer the research task, call generate_report.+1. Go coarse-to-fine: first narrow the corpus with navigation tools, then search only if needed.+2. After a navigation tool returns passages, judge whether they already answer the task.+ If they do, call generate_report immediately instead of searching further.+3. Only use hybrid_search / broad search tools when navigation did not yield sufficient evidence.+4. Use think_tool to analyze results after each step.+5. When you are confident enough to answer the research task, call generate_report.Tool call format: output exactly one JSON tool call per round:<tool_call>{{"name": "tool_name", "arguments": {{"parameter_name": "value"}} }}</tool_call>diff --git a/rag/advanced_rag/harness/tools/__init__.py b/rag/advanced_rag/harness/tools/__init__.pyindex bddd239855..16050e654e 100644--- a/rag/advanced_rag/harness/tools/__init__.py+++ b/rag/advanced_rag/harness/tools/__init__.py@@ -14,23 +14,26 @@ register_tool("web_search", _search_schema("web_search", "Internet search"), webregister_tool("structured_query", _search_schema("structured_query", "SQL search"), structured_query)# Navigation tools (require compilation)-from rag.advanced_rag.harness.tools.navigation import catalog_navigate, dataset_navigate, mindmap_navigate+from rag.advanced_rag.harness.tools.navigation import ontology_navigate, dataset_navigation_by_tree, mindmap_navigate-# catalog_navigate covers both the tree/TOC outline and the page index.+# ontology_navigate covers both the tree/TOC outline and the page index.register_tool(- "catalog_navigate",- _navigate_schema("catalog_navigate", "Get question-related chunks from the document's catalog (table of contents / page index)"),- catalog_navigate,+ "ontology_navigate",+ _navigate_schema("ontology_navigate", "Get question-related chunks from the given documents catalog (tree / page index / mind map). It always follows dataset navigation."),+ ontology_navigate,requires_compilation=True,- compilation_type=("toc", "page_index"),+ compilation_type=("toc", "page_index", "mindmap"),)register_tool("mindmap_navigate", _navigate_schema("mindmap_navigate", "Get question-related chunks from the document's mindmap"), mindmap_navigate, requires_compilation=True, compilation_type="mindmap")register_tool(- "dataset_navigate",- _navigate_schema("dataset_navigate", "Find the most relevant documents via the dataset map, then search within them"),- dataset_navigate,+ "dataset_navigation_by_tree",+ _navigate_schema(+ "dataset_navigation_by_tree",+ "Find the documents most relevant to the question via the dataset map; returns their document IDs (later navigation/exploration tools are automatically scoped to them).",+ ),+ dataset_navigation_by_tree,requires_compilation=True,compilation_type="tree",)diff --git a/rag/advanced_rag/harness/tools/gating.py b/rag/advanced_rag/harness/tools/gating.pyindex fb208e44f4..3605c1a6ab 100644--- a/rag/advanced_rag/harness/tools/gating.py+++ b/rag/advanced_rag/harness/tools/gating.py@@ -10,12 +10,12 @@ SEARCH_PHASES = {"locate": {"goal": "Locate documents or regions that may contain the answer.","tools_priority": [- "dataset_navigate",- "catalog_navigate",+ "dataset_navigation_by_tree",+ "ontology_navigate","mindmap_navigate",- "wiki_query","hybrid_search","bm25_search",+ "wiki_query",],"max_returned": 5,"tool_hint": "Prefer navigation tools to locate document regions before directly searching keywords.",@@ -70,18 +70,16 @@ def compilation_available(tool_name: str, compilation_map: dict) -> bool:return any(bool(comp_types & set(comps)) for comps in compilation_map.values())-def tool_fits_context(tool_name: str, context: OrchestratorContext) -> bool:+def tool_fits_context(tool_name: str, context: OrchestratorContext, has_routed_scope: bool = False) -> bool:"""Check if a tool is sensible given current search context."""if tool_name.startswith("inspector_") and not context.has_any_chunks():return False- if tool_name == "catalog_navigate" and not context.current_claim:+ if tool_name in {"ontology_navigate", "mindmap_navigate"} and not has_routed_scope:return False- if tool_name == "dataset_navigate" and not context.current_claim:+ if tool_name == "dataset_navigation_by_tree" and not context.current_claim:return Falseif tool_name == "graph_explore" and not context.last_entity:return False- if tool_name == "mindmap_navigate" and not context.current_claim:- return Falsereturn True@@ -90,6 +88,7 @@ def get_gated_tools(available_tools: list[str],compilation_map: dict[str, set[str]],context: OrchestratorContext,+ has_routed_scope: bool = False,) -> list[dict]:"""Filter, sort, and gate tools by phase priority and context."""phase_config = SEARCH_PHASES.get(phase)@@ -102,7 +101,7 @@ def get_gated_tools(continueif not compilation_available(tool_name, compilation_map):continue- if not tool_fits_context(tool_name, context):+ if not tool_fits_context(tool_name, context, has_routed_scope):continuesorted_tools.append(tool_name)diff --git a/rag/advanced_rag/harness/tools/navigation.py b/rag/advanced_rag/harness/tools/navigation.pyindex 898514e3bc..4d52cc9e8d 100644--- a/rag/advanced_rag/harness/tools/navigation.py+++ b/rag/advanced_rag/harness/tools/navigation.py@@ -9,7 +9,7 @@ Knowledge compilation writes every template kind into the same graph rows(``{"entities": [...], "relations": [...]}``), so the two tools share oneimplementation and differ only in which *kinds* they read:-* ``catalog_navigate`` — the document's layout: tree / TOC, page index, RAPTOR.+* ``ontology_navigate`` — the document's layout: tree / TOC, page index, RAPTOR.* ``mindmap_navigate`` — the concept mindmap.Both take the same ``keywords`` the search tools do — keywords drive query@@ -105,7 +105,7 @@ async def _load_compiled_structure(tools, doc_id: str, kinds: set) -> dict:)return settings.docStoreConn.get_fields(res, fields) or {}except Exception:- _LOG.exception("catalog_navigate: failed reading compiled structure for doc=%s", doc_id)+ _LOG.exception("ontology_navigate: failed reading compiled structure for doc=%s", doc_id)return {}rows = dict(await _query({"doc_id": [doc_id], "knowledge_graph_kwd": ["graph"]}, 1000))@@ -156,27 +156,6 @@ def _render_structure(entities: list[dict], relations: list[dict]) -> str:return "\n".join(lines)-def _entity_chunk_ids(entities: list[dict], wanted_names: list[str]) -> list[str]:- """Union the source_chunk_ids of the entities the model called relevant.-- Matches on ``name`` or any alias, case-insensitively. Relations carry no- source_chunk_ids, so entities are the only evidence anchor.- """- wanted = {n.strip().lower() for n in wanted_names if isinstance(n, str) and n.strip()}- ids: list[str] = []- seen: set[str] = set()- for e in entities:- names = {(e.get("name") or "").strip().lower()}- names.update((a or "").strip().lower() for a in (e.get("aliases") or []))- if not (names & wanted):- continue- for cid in e.get("source_chunk_ids") or []:- if isinstance(cid, str) and cid and cid not in seen:- seen.add(cid)- ids.append(cid)- return ids--async def _load_chunks_by_ids(tools, doc_id: str, chunk_ids: list[str]) -> list[dict]:"""Fetch chunks by their ids from the doc store."""if not chunk_ids:@@ -207,7 +186,7 @@ async def _load_chunks_by_ids(tools, doc_id: str, chunk_ids: list[str]) -> list[)rows = settings.docStoreConn.get_fields(res, fields) or {}except Exception:- _LOG.exception("catalog_navigate: failed loading evidence chunks for doc=%s", doc_id)+ _LOG.exception("ontology_navigate: failed loading evidence chunks for doc=%s", doc_id)return []chunks = []@@ -271,87 +250,78 @@ async def _ask_structure(tools, topic: str, entities: list[dict], relations: lisreturn answer, relevant-async def _navigate_compiled(+async def _navigate_within_doc(tools,topic: str,keywords: str,doc_scope: list[str] | None,kinds: set,- label: str,- noun: str,-) -> dict:- """Answer ``topic`` from the compiled structure of the docs in ``doc_scope``.-- Shared by :func:`catalog_navigate` and :func:`mindmap_navigate` — compilation- writes every template kind into the same graph rows, so the tools differ only- in which ``kinds`` they read and how they describe themselves.+) -> list[dict]:+ """Return the chunk texts behind the entities the model finds relevant.- Falls back to a plain hybrid search when there is no doc scope, no compiled- structure of these kinds, or no source chunks behind the relevant entities.+ Reads the compiled ``kinds`` structure of every doc in ``doc_scope`` — the+ tree / page-index catalog, or the concept mindmap — asks the chat model+ which of those entities are relevant to the question, and returns the chunks+ attached to the selected entities' ``source_chunk_ids``.- :returns: ``{"answer": str, "chunks": [...], "doc_aggs": [...]}``+ Routing only — no fallback search. Returns ``[]`` when there is no doc scope,+ no question/keywords, no compiled structure of these kinds, no relevant+ entity, or no source chunks behind the selected entities."""- from rag.advanced_rag.harness.tools.search import _narrow_by_keywords, hybrid_search-if not doc_scope:- _LOG.info(f"[{label}] No document scope given — falling back to a normal search.")- return await hybrid_search(tools, query=topic, keywords=keywords)+ return []+ query = " ".join(part for part in ((topic or "").strip(), (keywords or "").strip()) if part).strip()+ if not query:+ return []+ # 1. List the compiled structure entities of each doc, tagged with their+ # originating doc_id so their chunks load from the right document.entities: list[dict] = []- relations: list[dict] = []- per_doc: list[tuple[str, list[dict]]] = []for doc_id in doc_scope:structure = await _load_compiled_structure(tools, doc_id, kinds)- if structure["entities"] or structure["relations"]:- per_doc.append((doc_id, structure["entities"]))- entities.extend(structure["entities"])- relations.extend(structure["relations"])-- if not entities and not relations:- _LOG.info(f"[{label}] These documents have no {noun} — falling back to a normal search.")- return await hybrid_search(tools, query=topic, keywords=keywords, doc_scope=doc_scope)+ for e in structure.get("entities") or []:+ if isinstance(e, dict) and (e.get("name") or "").strip():+ entities.append({**e, "_doc_id": doc_id})+ if not entities:+ return []- _LOG.info("[%s] Read an outline of %d entity(ies) and %d relation(s).", label, len(entities), len(relations))+ # 2. Ask the model which entities are relevant to the question.+ selected = await _ask_nav_select(tools, query, entities, "entities", _MAX_ENTITIES)+ if not selected:+ return []- answer, relevant = await _ask_structure(tools, topic, entities, relations, noun, label)+ # 3. Load the chunks attached to the selected entities (grouped by doc).+ ids_by_doc: dict[str, list[str]] = {}+ seen: set[tuple[str, str]] = set()+ for e in selected:+ doc_id = e.get("_doc_id")+ if not doc_id:+ continue+ for cid in e.get("source_chunk_ids") or []:+ if isinstance(cid, str) and cid and (doc_id, cid) not in seen:+ seen.add((doc_id, cid))+ ids_by_doc.setdefault(doc_id, []).append(cid)- # Pull the source text behind the relevant entities, per originating doc.chunks: list[dict] = []- for doc_id, doc_entities in per_doc:- ids = _entity_chunk_ids(doc_entities, relevant)- if ids:- chunks.extend(await _load_chunks_by_ids(tools, doc_id, ids))-- if not chunks:- _LOG.info(f"[{label}] No source text behind those entities — falling back to a normal search.")- return await hybrid_search(tools, query=topic, keywords=keywords, doc_scope=doc_scope)-- before = len(chunks)- narrowed = _narrow_by_keywords(chunks, keywords)- if narrowed:- chunks = narrowed- _LOG.info("[%s] Pulled %d source passage(s) behind those entities, kept %d after keyword filtering.", label, before, len(chunks))- else:- _LOG.info("[%s] Keyword filtering removed all %d passage(s); restoring unfiltered set.", label, before)-- return {"answer": answer, "chunks": chunks, "doc_aggs": _doc_aggs(chunks)}+ for doc_id, ids in ids_by_doc.items():+ chunks.extend(await _load_chunks_by_ids(tools, doc_id, ids))+ _LOG.info("[Navigation] Selected %d entity(ies) → %d source chunk(s).", len(selected), len(chunks))+ return chunks-async def catalog_navigate(tools, topic: str, keywords: str = "", doc_scope: list[str] | None = None) -> dict:- """Answer from the documents' compiled catalog (tree / TOC, page index, RAPTOR).+async def ontology_navigate(tools, topic: str, keywords: str = "", doc_scope: list[str] | None = None) -> dict:+ """Answer from the documents' compiled catalog (tree / page index).- :returns: ``{"answer": str, "chunks": [...], "doc_aggs": [...]}``+ :returns: ``{"answer": "", "chunks": [...], "doc_aggs": [...]}``"""- _LOG.info(f'[Catalog navigation] Looking through the document catalog for "{topic}" (keywords: {keywords})')- return await _navigate_compiled(- tools,- topic,- keywords,- doc_scope,- kinds=_CATALOG_KINDS,- label="Catalog navigation",- noun="document catalog",- )+ if not doc_scope:+ doc_scope = []+ _LOG.info(f'[Ontology navigation] Looking through the document catalog for "{topic}" (keywords: {keywords}) in doc: {len(doc_scope)}')+ if not doc_scope:+ _LOG.info(f'[Ontology navigation] No doc scope provided: "{topic}" (keywords: {keywords})')+ return {"answer": "", "chunks": [], "doc_aggs": []}+ chunks = await _navigate_within_doc(tools, topic, keywords, doc_scope, _CATALOG_KINDS)+ return {"answer": "", "chunks": chunks, "doc_aggs": _doc_aggs(chunks)}async def mindmap_navigate(tools, topic: str, keywords: str = "", doc_scope: list[str] | None = None) -> dict:@@ -360,18 +330,13 @@ async def mindmap_navigate(tools, topic: str, keywords: str = "", doc_scope: lis``topic`` (not ``concept``) — the parameter name must match the registered``_navigate_schema``, otherwise every LLM call raises a TypeError.- :returns: ``{"answer": str, "chunks": [...], "doc_aggs": [...]}``+ :returns: ``{"answer": "", "chunks": [...], "doc_aggs": [...]}``"""- _LOG.info(f'[Mindmap navigation] Following the concept mindmap for "{topic}" (keywords: {keywords})')- return await _navigate_compiled(- tools,- topic,- keywords,- doc_scope,- kinds=_MINDMAP_KINDS,- label="Mindmap navigation",- noun="concept mindmap",- )+ if not doc_scope:+ doc_scope = []+ _LOG.info(f'[Mindmap navigation] Following the concept mindmap for "{topic}" (keywords: {keywords}) in doc: {len(doc_scope)}')+ chunks = await _navigate_within_doc(tools, topic, keywords, doc_scope, _MINDMAP_KINDS)+ return {"answer": "", "chunks": chunks, "doc_aggs": _doc_aggs(chunks)}# ── Dataset navigation (document router) ────────────────────────────────────@@ -379,75 +344,196 @@ async def mindmap_navigate(tools, topic: str, keywords: str = "", doc_scope: lis_NAV_MAX_DOCS = 8 # documents the nav tree routes a query to_NAV_MAX_HITS_PER_KB = 8+# Tree-walk router tunables.+_NAV_MAX_CLUSTERS = 500 # top-level clusters listed / rendered to the LLM+_NAV_CHILDREN_PAGE_SIZE = 1000 # children fetched per node+_NAV_TREE_MAX_DEPTH = 6 # BFS depth cap when descending sub-clusters to leaves+_NAV_TREE_MAX_LEAVES = 300 # document leaves rendered to the doc-select LLM-async def dataset_navigate(tools, topic: str, keywords: str = "", doc_scope: list[str] | None = None) -> dict:- """Route the query to the most relevant documents via the dataset nav tree,- then search within only those documents.+_NAV_SELECT_SYSTEM = """You are routing a question through a dataset's navigation tree.- The nav tree is a KB-level RAPTOR-style summary of every document; searching- it narrows the corpus to the handful of documents worth reading before the- real chunk retrieval runs (coarse-to-fine). Falls back to a plain hybrid- search when the KB has no nav tree or nothing routes.+You are given a QUESTION and a numbered list of {noun}, each with a name and a short description.+Choose the {noun} most likely to contain information relevant to answering the question.- :returns: ``{"answer": "", "chunks": [...], "doc_aggs": [...]}``+Rules:+1. Judge only from the names and descriptions shown.+2. Be selective — include an item only if it is plausibly relevant. Include several when several are equally plausible.+3. If none are clearly relevant, return an empty list.+4. Return the bracketed index numbers of the chosen {noun}.++Output ONLY JSON, no prose, no code fences:+{{"relevant": [<index>, ...]}}"""+++async def _ask_nav_select(tools, query: str, items: list[dict], noun: str, max_items: int) -> list[dict]:+ """Ask the chat model which of ``items`` are relevant to ``query``.++ Items are rendered as a numbered list of ``name`` (+ optional ``doc_count``)+ and ``description``; the model returns the chosen indices. Index-based (not+ id-based) so the model never has to reproduce opaque doc ids or exact names.+ Returns the selected item dicts (a subset of ``items``), or ``[]`` when the+ model declines or the call fails."""- from rag.advanced_rag.harness.tools.search import hybrid_search+ if not items:+ return []+ from rag.prompts.generator import form_message, message_fit_in++ capped = items[:max_items]+ lines = []+ for i, it in enumerate(capped):+ name = str(it.get("name") or "").strip() or f"item-{i}"+ desc = str(it.get("description") or "").strip().replace("\n", " ")+ extra = f" [{it['doc_count']} docs]" if it.get("doc_count") else ""+ lines.append(f"[{i}] {name}{extra}: {desc[:300]}")++ system = _NAV_SELECT_SYSTEM.format(noun=noun)+ user = f"Question:\n{query}\n\n{noun.capitalize()} (numbered):\n" + "\n".join(lines) + "\n\nOutput JSON:"+ try:+ _, msg = message_fit_in(form_message(system, user), tools.chat_mdl.max_length)+ ans = await tools.chat_mdl.async_chat(msg[0]["content"], msg[1:], {"temperature": 0.2})+ if isinstance(ans, tuple):+ ans = ans[0]+ cleaned = re.sub(r"^.*</think>", "", ans, flags=re.DOTALL)+ cleaned = re.sub(r"```(?:json)?\s*|\s*```", "", cleaned).strip()+ verdict = json_repair.loads(cleaned) or {}+ except Exception:+ _LOG.exception("[Dataset navigation] LLM %s selection failed", noun)+ return []+ if not isinstance(verdict, dict):+ return []+ raw = verdict.get("relevant")+ if not isinstance(raw, list):+ return []++ out: list[dict] = []+ seen_idx: set[int] = set()+ for r in raw:+ try:+ idx = int(r)+ except (TypeError, ValueError):+ continue+ if 0 <= idx < len(capped) and idx not in seen_idx:+ seen_idx.add(idx)+ out.append(capped[idx])+ return out- query = topic- _LOG.info(f'[Dataset navigation] Finding the most relevant documents for "{query}" (keywords: {keywords})')- # Caller already narrowed the corpus — just retrieve within it.- if doc_scope:- return await hybrid_search(tools, query=query, keywords=keywords, doc_scope=doc_scope)+async def _collect_nav_leaves(dataset_api_service, clusters: list[dict]) -> list[dict]:+ """BFS from the selected clusters down to their document leaves.++ Each cluster carries ``name`` + ``kb``. A node's children are either document+ leaves (``type == "doc"`` — collected, deduped by ``doc_id``) or sub-clusters+ (descended, depth- and count-capped).+ """+ leaves: list[dict] = []+ seen_docs: set[str] = set()+ seen_nodes: set[tuple] = set()+ frontier: list[tuple] = [(c["kb"], c["name"], 0) for c in clusters if c.get("name")]++ while frontier and len(leaves) < _NAV_TREE_MAX_LEAVES:+ kb, name, depth = frontier.pop(0)+ node_key = (kb.id, name)+ if node_key in seen_nodes:+ continue+ seen_nodes.add(node_key)+ try:+ ok, data = await dataset_api_service.list_nav_children(kb.id, kb.tenant_id, name, page=1, page_size=_NAV_CHILDREN_PAGE_SIZE)+ except Exception:+ _LOG.exception("[Dataset navigation] list_nav_children failed for kb=%s node=%s", kb.id, name)+ continue+ if not ok or not isinstance(data, dict):+ continue+ for item in data.get("items") or []:+ if item.get("type") == "doc":+ did = str(item.get("doc_id") or "").strip()+ if did and did not in seen_docs:+ seen_docs.add(did)+ leaves.append({**item, "kb": kb})+ if len(leaves) >= _NAV_TREE_MAX_LEAVES:+ break+ elif item.get("type") == "cluster" and item.get("name") and depth + 1 < _NAV_TREE_MAX_DEPTH:+ frontier.append((kb, item["name"], depth + 1))+ return leaves+++def _nav_cluster_names(clusters: list[dict]) -> str:+ names = [str(c.get("name") or "").strip() for c in clusters]+ return ", ".join(n for n in names if n) or "none"+++async def dataset_navigation_by_tree(tools, topic: str, keywords: str = "", doc_scope: list[str] | None = None) -> list[str]:+ """Return the ``doc_id``s most relevant to the question / keywords by walking+ the dataset nav tree with the chat model.++ The nav tree is a KB-level RAPTOR-style summary of every document. Two LLM+ passes narrow the corpus coarse-to-fine:++ 1. List the top-level clusters (``list_nav_clusters``).+ 2. Ask the model which clusters are relevant to the question.+ 3. Descend those clusters to their document leaves (``list_nav_children``,+ recursing sub-clusters).+ 4. Ask the model which documents are worth reading.++ Returns the routed ``doc_id`` list (capped at ``_NAV_MAX_DOCS``), or ``[]``+ when no question/keywords are given, there is no cluster tree, or the model+ finds nothing relevant. This function only routes — it does not retrieve.+ """+ query = " ".join(part for part in ((topic or "").strip(), (keywords or "").strip()) if part).strip()+ if not query:+ return []++ _LOG.info('[Dataset navigation] Walking the dataset tree for "%s"', query)- from rag.advanced_rag.knowlege_compile.dataset_nav import search_dataset_nav+ from api.apps.services import dataset_api_service- candidates: list[tuple[float, str]] = []- nav_entities: list[dict] = []- seen: set[str] = set()- seen_nodes: set[str] = set()- for kb in getattr(tools, "kbs", []) or []:+ kbs = getattr(tools, "kbs", []) or []++ # 1. List every top-level cluster across the bound KBs (tagged with its KB).+ clusters: list[dict] = []+ for kb in kbs:try:- hits = await search_dataset_nav(- kb.tenant_id,- kb.id,- query,- embd_mdl=getattr(tools, "embed_mdl", None),- top_k=_NAV_MAX_HITS_PER_KB,- )+ ok, data = await dataset_api_service.list_nav_clusters(kb.id, kb.tenant_id, page=1, page_size=_NAV_MAX_CLUSTERS)except Exception:- _LOG.exception("[Dataset navigation] nav-tree search failed for kb=%s", kb.id)+ _LOG.exception("[Dataset navigation] list_nav_clusters failed for kb=%s", kb.id)continue- for h in hits:- score = float(h.get("score") or 0.0)- node_name = str(h.get("name") or "")- if node_name and node_name not in seen_nodes:- seen_nodes.add(node_name)- nav_entities.append(- {- "name": node_name,- "type": h.get("type") or "dataset_nav",- "description": h.get("description") or "",- }- )- for did in h.get("doc_ids") or []:- if did and did not in seen:- seen.add(did)- candidates.append((score, did))-- candidates.sort(key=lambda item: item[0], reverse=True)- routed = [did for _, did in candidates[:_NAV_MAX_DOCS]]- if not routed:- _LOG.info("[Dataset navigation] No dataset map here — falling back to a normal search.")- return await hybrid_search(tools, query=query, keywords=keywords)-- _LOG.info("[Dataset navigation] Routed to %d document(s); searching within them.", len(routed))- answer = ""- if nav_entities:- answer, _ = await _ask_structure(tools, query, nav_entities, [], "dataset map", "Dataset navigation")- result = await hybrid_search(tools, query=query, keywords=keywords, doc_scope=routed)- result["answer"] = answer- return result+ if not ok or not isinstance(data, dict):+ continue+ for item in data.get("items") or []:+ if item.get("type") == "cluster" and item.get("name"):+ clusters.append({**item, "kb": kb})++ if not clusters:+ _LOG.info("[Dataset navigation] no cluster there.")+ return []++ # 2. Ask the model which clusters are relevant. Nothing relevant → [].+ selected_clusters = await _ask_nav_select(tools, query, clusters, "clusters", _NAV_MAX_CLUSTERS)+ if not selected_clusters:+ _LOG.info("[Dataset navigation] no cluster found.")+ return []+ _LOG.info("[Dataset navigation] %d/%d cluster(s) selected.", len(selected_clusters), len(clusters))++ # 3. Descend the selected clusters to their document leaves.+ leaves = await _collect_nav_leaves(dataset_api_service, selected_clusters)+ if not leaves:+ _LOG.info("[Dataset navigation] no leaf under selected cluster %s.", _nav_cluster_names(selected_clusters))+ return []++ # 4. Ask the model which documents to look into. Nothing relevant → [].+ selected_docs = await _ask_nav_select(tools, query, leaves, "documents", _NAV_TREE_MAX_LEAVES)+ if not selected_docs:+ _LOG.info("[Dataset navigation] no doc selected under cluster %s.", _nav_cluster_names(selected_clusters))+ return []++ routed: list[str] = []+ seen_docs: set[str] = set()+ for d in selected_docs:+ did = str(d.get("doc_id") or "").strip()+ if did and did not in seen_docs:+ seen_docs.add(did)+ routed.append(did)+ _LOG.info("[Dataset navigation] Routed to %d document(s).", len(routed))+ return routed[:_NAV_MAX_DOCS]# ── Knowledge-graph exploration ─────────────────────────────────────────────diff --git a/rag/advanced_rag/harness/tools/registry.py b/rag/advanced_rag/harness/tools/registry.pyindex a82dd08f32..60cf8b5f3f 100644--- a/rag/advanced_rag/harness/tools/registry.py+++ b/rag/advanced_rag/harness/tools/registry.py@@ -61,8 +61,9 @@ def _navigate_schema(name: str, desc: str) -> dict:"parameters": {"type": "object","properties": {- "topic": {"type": "string", "description": "the topic to navigate to."},- "keywords": {"type": "string", "description": "the keywords used for searching split by space or ','."},+ "topic": {"type": "string", "description": "the query/keywords to navigate to."},+ "keywords": {"type": "string", "description": "the query/keywords used for searching split by space or ','."},+ "doc_scope": {"type": "array", "items": {"type": "string"}, "description": "The doc ID list to narrow down the searching scope. None or empty value means no limitation at all."},},"required": ["topic"],},diff --git a/rag/advanced_rag/harness/types.py b/rag/advanced_rag/harness/types.pyindex 3bd2328b39..564e9f9fe7 100644--- a/rag/advanced_rag/harness/types.py+++ b/rag/advanced_rag/harness/types.py@@ -124,7 +124,10 @@ class SufficiencyVerdict:@dataclassclass ToolResult:- chunks: list[dict]+ chunks: list[dict] = field(default_factory=list)+ # Doc-id list from routing tools (e.g. dataset_navigation_by_tree) that+ # narrow the corpus to the relevant documents instead of returning chunks.+ docs: list[str] | None = Nonemetadata: dict = field(default_factory=dict)error: str | None = None