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
Feat: compilation result navigation in agentic search (#17002)
Kevin Hud5d04ad6393f
diff --git a/rag/advanced_rag/agentic_rag.py b/rag/advanced_rag/agentic_rag.pyindex 01eada141e..0e214a4276 100644--- a/rag/advanced_rag/agentic_rag.py+++ b/rag/advanced_rag/agentic_rag.py@@ -116,6 +116,11 @@ class RAGTools:# ``[ID:n]`` markers index), so the caller can resolve references.self.kbinfos: dict[str, list] = {"chunks": [], "doc_aggs": []}+ # Per-request retrieval cache keyed by the effective query + scope, so+ # the same question is never retrieved twice within one turn (e.g.+ # pre_search vs. an identical claim search in orchestrator_loop).+ self.search_cache: dict = {}+# The two tools the outer LLM may bind. They are NOT auto-bound here —# the agentic-search flow drives the graph directly — but callers that# want a tool surface can do ``chat_mdl.bind_tools(tools=rag_tools.tools)``.diff --git a/rag/advanced_rag/agentic_rag_graph.py b/rag/advanced_rag/agentic_rag_graph.pyindex fb87300cc1..ba8a8c0bc7 100644--- a/rag/advanced_rag/agentic_rag_graph.py+++ b/rag/advanced_rag/agentic_rag_graph.py@@ -160,11 +160,11 @@ def build_agentic_graph(tools, token_queue: asyncio.Queue, gen_conf: dict | None# ── Node: formalize_question ──async def formalize_question(state: AgenticState) -> dict:msgs = state.get("messages") or []- _LOG.info("[formalize_question] IN | %d msg(s)", len(msgs))+ _LOG.info("[Formalizing the question] Reading the conversation (%d message(s)) to work out the standalone question...", len(msgs))q, kw = await tools.formalize(msgs)q = (q or "").strip()kw = (kw or "").strip()- _LOG.info("[formalize_question] OUT | question=%s | keywords=%s", _snip(q), _snip(kw))+ _LOG.info("[Formalizing the question] Understood the question as: \"%s\" — searching with keywords: %s", _snip(q), _snip(kw))return {"question": q,"keywords": kw,@@ -191,23 +191,23 @@ def build_agentic_graph(tools, token_queue: asyncio.Queue, gen_conf: dict | None"""route = state.get("route")if not route or not getattr(route, "requires_decomposition", False):- _LOG.info("[pre_search] SKIP | direct/low mode (no decomposition)")+ _LOG.info("[Preliminary search] Skipping the first look — this question goes straight to a single search.")return {"seed_chunks": []}from rag.advanced_rag.harness.tools.search import hybrid_searchq = state.get("question", "")kw = state.get("keywords", "")- _LOG.info("[pre_search] IN | question=%s | keywords=%s", _snip(q), _snip(kw))+ _LOG.info("[Preliminary search] Taking a first look in the knowledge base for: \"%s\" (keywords: %s)", _snip(q), _snip(kw))try:result = await hybrid_search(tools, query=q, keywords=kw)except Exception:- _LOG.exception("[pre_search] hybrid_search failed")+ _LOG.exception("[Preliminary search] hybrid_search failed")return {"seed_chunks": []}chunks = result.get("chunks", []) or []_merge_result_into_kbinfos(tools, result)- _LOG.info("[pre_search] OUT | %d seed chunk(s), kbinfos now %d", len(chunks), len(tools.kbinfos.get("chunks", [])))+ _LOG.info("[Preliminary search] First look found %d passage(s); %d gathered so far.", len(chunks), len(tools.kbinfos.get("chunks", [])))return {"seed_chunks": chunks}# ── Node: planner ──@@ -230,7 +230,8 @@ def build_agentic_graph(tools, token_queue: asyncio.Queue, gen_conf: dict | Noneabstain = state.get("abstain", False)empty_result = state.get("empty_result", False)- _LOG.info("[formalize_answer] IN | question=%s | chunks=%d | partial=%s | abstain=%s", _snip(question), len(kbinfos["chunks"]), partial, abstain)+ _note = " — partial answer, some gaps remain" if partial else (" — not enough evidence to answer" if abstain else "")+ _LOG.info("[Composing the answer] Writing the final answer to \"%s\" from %d gathered passage(s)%s.", _snip(question), len(kbinfos["chunks"]), _note)tools.kbinfos = kbinfos@@ -299,12 +300,9 @@ def build_agentic_graph(tools, token_queue: asyncio.Queue, gen_conf: dict | Nonereturn g.compile()-# ── Runner ──--async def run_agentic_rag(tools, messages: list, max_loops: int = 3, gen_conf: dict | None = None):"""Drive the agentic-search graph, yielding answer-token strings."""- _LOG.info("[agentic-rag] RUN START | %d message(s), max_loops=%d", len(messages or []), max_loops)+ _LOG.info("[Agentic RAG] Starting research to answer your question...")token_queue: asyncio.Queue = asyncio.Queue()graph = build_agentic_graph(tools, token_queue, gen_conf=gen_conf)@@ -340,7 +338,7 @@ async def run_agentic_rag(tools, messages: list, max_loops: int = 3, gen_conf: dif isinstance(final_kb, dict) and final_kb.get("chunks"):tools.kbinfos = final_kb- _LOG.info("[agentic-rag] RUN END | streamed=%s, loops=%d, chunks=%d", produced, state.get("loop", 0), len((state.get("kbinfos") or {}).get("chunks", [])))+ _LOG.info("[Agentic RAG] Research complete — %d passage(s) gathered after %d round(s).", len((state.get("kbinfos") or {}).get("chunks", [])), state.get("loop", 0))if not produced and holder.get("error"):yield "I couldn't complete the search due to an internal error."diff --git a/rag/advanced_rag/harness/agent.py b/rag/advanced_rag/harness/agent.pyindex 31061e443e..6c154b723a 100644--- a/rag/advanced_rag/harness/agent.py+++ b/rag/advanced_rag/harness/agent.py@@ -338,8 +338,13 @@ def _fmt_tool_list(defs: list[dict]) -> str:def _fmt_tool_result(result: ToolResult) -> str:if result.error:return f"[tool error] {result.error}"- chunks = result.chunks[:3]- texts = [c.get("content_with_weight", c.get("text", ""))[:300] for c in chunks]- if not texts:+ parts: list[str] = []+ # Some tools (catalog_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:+ parts.append(f"Answer: {answer}")+ parts.extend(c.get("content_with_weight", c.get("text", ""))[:300] for c in result.chunks[:3])+ if not parts:return "[no results found]"- return "\n\n".join(texts)+ return "\n\n".join(parts)diff --git a/rag/advanced_rag/harness/config.py b/rag/advanced_rag/harness/config.pyindex af9ffbd42e..0266ec4716 100644--- a/rag/advanced_rag/harness/config.py+++ b/rag/advanced_rag/harness/config.py@@ -52,8 +52,7 @@ THINKING_MODES: dict[str, ExecutionStrategy] = {available_tools=["hybrid_search","web_search",- "toc_navigate",- "page_index_navigate",+ "catalog_navigate","graph_explore","inspector_open_context","inspector_compare",@@ -79,8 +78,7 @@ THINKING_MODES: dict[str, ExecutionStrategy] = {"bm25_search","web_search","structured_query",- "toc_navigate",- "page_index_navigate",+ "catalog_navigate","mindmap_navigate","graph_explore","wiki_query",diff --git a/rag/advanced_rag/harness/orchestrator/__init__.py b/rag/advanced_rag/harness/orchestrator/__init__.pyindex 66b6e35497..f2cd291b4d 100644--- a/rag/advanced_rag/harness/orchestrator/__init__.py+++ b/rag/advanced_rag/harness/orchestrator/__init__.py@@ -20,7 +20,7 @@ async def orchestrator_loop(state: dict, tools) -> dict:mode_label = route.thinking_mode if isinstance(route, dict) else route.thinking_modemode = get_mode(mode_label)- _LOG.info("[orchestrator] strategy=%s mode=%s", mode.execution_strategy, mode_label)+ _LOG.info("[Orchestrator] Researching with the \"%s\" approach (%s thinking).", mode.execution_strategy, mode_label)if mode.execution_strategy == "direct_search":return await direct_search(state, tools)diff --git a/rag/advanced_rag/harness/orchestrator/agentic.py b/rag/advanced_rag/harness/orchestrator/agentic.pyindex 844e0306f8..9ed7a6463d 100644--- a/rag/advanced_rag/harness/orchestrator/agentic.py+++ b/rag/advanced_rag/harness/orchestrator/agentic.py@@ -43,7 +43,7 @@ async def agentic_research(state: dict, tools) -> dict:for cycle in range(mode.max_orchestrator_cycles):ctx.iteration = cycle- _LOG.info("[agentic] cycle %d/%d, claims: %d unverified", cycle + 1, mode.max_orchestrator_cycles, sum(1 for c in ctx.claims if not c.is_verified))+ _LOG.info("[Agentic research] Research round %d of %d — %d step(s) still unanswered.", cycle + 1, mode.max_orchestrator_cycles, sum(1 for c in ctx.claims if not c.is_verified))# ── Step A: Research unverified claims (parallel if mode allows) ──unverified = [c for c in ctx.claims if not c.is_verified]@@ -54,18 +54,16 @@ async def agentic_research(state: dict, tools) -> dict:for i in range(0, len(unverified), batch_size):batch = unverified[i : i + batch_size]_LOG.info(- "[agentic] batch start cycle=%d offset=%d size=%d claim_ids=%s",+ "[Agentic research] Round %d: researching %d step(s) in parallel: %s",cycle + 1,- i,len(batch),- [c.claim_id for c in batch],+ "; ".join(f'"{c.description}"' for c in batch),)tasks = [_run_claim_research(c, tools, pipeline, ctx, mode, compilation_map) for c in batch]agent_results = await asyncio.gather(*tasks)_LOG.info(- "[agentic] batch done cycle=%d offset=%d size=%d",+ "[Agentic research] Round %d: finished researching %d step(s).",cycle + 1,- i,len(agent_results),)@@ -93,7 +91,7 @@ async def agentic_research(state: dict, tools) -> dict:description=dc,))- _LOG.info("[agentic] discovered new claim: %s", dc)+ _LOG.info("[Agentic research] Found a new angle worth researching: \"%s\"", dc)# ── Step B: Sufficiency Check ──all_chunks = {i: c for i, c in enumerate(tools.kbinfos.get("chunks", []))}@@ -110,7 +108,7 @@ async def agentic_research(state: dict, tools) -> dict:mode.max_orchestrator_cycles,)- _LOG.info("[agentic] cycle=%d verdict=%s score=%.2f action=%s", cycle, verdict.status, verdict.score, action)+ _LOG.info("[Agentic research] Round %d: evidence looks %s (confidence %.0f%%) — next: %s", cycle + 1, verdict.status, verdict.score * 100, action)if action == "ANSWER":return _finalize(ctx, tools, partial=False)@@ -142,7 +140,7 @@ async def _run_claim_research(mode,compilation_map: dict,) -> dict:- _LOG.info("[agentic] claim start id=%s desc=%s", claim.claim_id, _snip(claim.description))+ _LOG.info("[Agentic research] Researching: \"%s\"", _snip(claim.description))try:result = await asyncio.wait_for(research_agent_loop(claim, tools, pipeline, ctx, mode, compilation_map),@@ -152,10 +150,9 @@ async def _run_claim_research(raiseexcept asyncio.TimeoutError:_LOG.warning(- "[agentic] claim timeout id=%s timeout=%ss desc=%s",- claim.claim_id,- CLAIM_RESEARCH_TIMEOUT_SECONDS,+ "[Agentic research] Gave up on \"%s\" — it took longer than %ss.",_snip(claim.description),+ CLAIM_RESEARCH_TIMEOUT_SECONDS,)return {"report": "",@@ -166,7 +163,7 @@ async def _run_claim_research("discovered_claims": [],}except Exception:- _LOG.exception("[agentic] claim failed id=%s desc=%s", claim.claim_id, _snip(claim.description))+ _LOG.exception("[Agentic research] Hit an error while researching \"%s\".", _snip(claim.description))return {"report": "","is_verified": False,@@ -177,12 +174,12 @@ async def _run_claim_research(}_LOG.info(- "[agentic] claim done id=%s verified=%s confidence=%.2f evidence=%d gaps=%d",- claim.claim_id,- result.get("is_verified", False),- float(result.get("confidence") or 0.0),+ "[Agentic research] Finished \"%s\" — %s, backed by %d passage(s) (confidence %.0f%%)%s.",+ _snip(claim.description),+ "answered" if result.get("is_verified") else "still unanswered",len(result.get("evidence_ids") or []),- len(result.get("gaps") or []),+ float(result.get("confidence") or 0.0) * 100,+ f", {len(result.get('gaps') or [])} gap(s) remain" if result.get("gaps") else "",)return resultdiff --git a/rag/advanced_rag/harness/orchestrator/direct.py b/rag/advanced_rag/harness/orchestrator/direct.pyindex 0059771a79..e7cdc32704 100644--- a/rag/advanced_rag/harness/orchestrator/direct.py+++ b/rag/advanced_rag/harness/orchestrator/direct.py@@ -11,13 +11,13 @@ async def direct_search(state: dict, tools) -> dict:"""Single hybrid search → merge into kbinfos."""question = state.get("question", "")keywords = state.get("keywords", "")- _LOG.info("[direct_search] question=%s | keywords=%s", question, keywords)+ _LOG.info("[Direct search] Looking up the knowledge base for: \"%s\" (keywords: %s)", question, keywords)result = await hybrid_search(tools, query=question, keywords=keywords)_merge_kbinfos(tools, result)if not _has_chunks(tools):- _LOG.info("[direct_search] no results found")+ _LOG.info("[Direct search] Found no matching passages.")return {"empty_result": True, "kbinfos": tools.kbinfos}return {"kbinfos": tools.kbinfos}diff --git a/rag/advanced_rag/harness/pipeline.py b/rag/advanced_rag/harness/pipeline.pyindex a099436aea..408bd05043 100644--- a/rag/advanced_rag/harness/pipeline.py+++ b/rag/advanced_rag/harness/pipeline.py@@ -119,7 +119,10 @@ def filter_available_tools(tool_names: list[str], compilation_map: dict[str, setcontinueif tool.get("requires_compilation"):comp_type = tool.get("compilation_type")- if comp_type and not any(comp_type in comps for comps in compilation_map.values()):+ # ``compilation_type`` may name one artifact or several (a tool that+ # reads either one is available when ANY of them is compiled).+ wanted = {comp_type} if isinstance(comp_type, str) else set(comp_type or ())+ if wanted and not any(wanted & comps for comps in compilation_map.values()):continueavailable.append(name)return availablediff --git a/rag/advanced_rag/harness/planner.py b/rag/advanced_rag/harness/planner.pyindex 072db5b739..9a73df019e 100644--- a/rag/advanced_rag/harness/planner.py+++ b/rag/advanced_rag/harness/planner.py@@ -39,7 +39,7 @@ async def planner_node(state: dict, tools) -> dict:_LOG.warning("planner: no route found, using defaults")return _default_plan(state.get("question", ""))- _LOG.info("[Planner] IN | question=%s type=%s", _snip(route.question), route.question_type)+ _LOG.info("[Planner] Working out how to research this %s question: \"%s\"", route.question_type, _snip(route.question))if not route.requires_decomposition:# Direct mode: single coarse claimreturn _direct_plan(route.question)@@ -105,7 +105,7 @@ async def planner_node(state: dict, tools) -> dict:claims=claims,max_iterations=mode.max_orchestrator_cycles,)- _LOG.info("[Planner] OUT | plan type=%s | claims=%d", plan_type, len(plan.claims))+ _LOG.info("[Planner] Broke the question into %d research step(s): %s", len(plan.claims), "; ".join(f'"{c.description}"' for c in plan.claims))return {"plan": plan, "claims": plan.claims}diff --git a/rag/advanced_rag/harness/tools/__init__.py b/rag/advanced_rag/harness/tools/__init__.pyindex 5be55f746c..de58a9c1af 100644--- a/rag/advanced_rag/harness/tools/__init__.py+++ b/rag/advanced_rag/harness/tools/__init__.py@@ -14,10 +14,17 @@ 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 toc_navigate, page_index_navigate, mindmap_navigate+from rag.advanced_rag.harness.tools.navigation import catalog_navigate, mindmap_navigate-register_tool("toc_navigate", _navigate_schema("toc_navigate", "Navigation with table of content"), toc_navigate, requires_compilation=True, compilation_type="toc")-register_tool("page_index_navigate", _navigate_schema("page_index_navigate", "Navigation with extracted titles"), page_index_navigate, requires_compilation=True, compilation_type="page_index")+# catalog_navigate covers both the tree/TOC outline and the page index — it reads+# whichever compiled catalog the doc has, so it is offered when either exists.+register_tool(+ "catalog_navigate",+ _navigate_schema("catalog_navigate", "Answer from the document's compiled catalog (table of contents / page index)"),+ catalog_navigate,+ requires_compilation=True,+ compilation_type=("toc", "page_index"),+)register_tool("mindmap_navigate", _navigate_schema("mindmap_navigate", "Navigate by mindmap"), mindmap_navigate, requires_compilation=True, compilation_type="mindmap")# Exploration tools (require compilation)diff --git a/rag/advanced_rag/harness/tools/exploration.py b/rag/advanced_rag/harness/tools/exploration.pyindex 9969b30a6a..f44856c1e1 100644--- a/rag/advanced_rag/harness/tools/exploration.py+++ b/rag/advanced_rag/harness/tools/exploration.py@@ -1,32 +1,32 @@-"""Exploration tools: knowledge graph and wiki lookup."""+"""Exploration tools: knowledge graph and wiki lookup.-import logging--_LOG = logging.getLogger(__name__)+``graph_explore`` lives in :mod:`navigation` (it shares the compiled-structure+machinery) and is re-exported here so the tool registry keeps one import point.+``wiki_query`` retrieves through ``hybrid_search`` and takes the same+``keywords`` the other search tools do — the keywords drive query expansion and+the keyword-sentence narrowing. Parameter names must match the registered+``_search_schema`` (``query`` + ``keywords``), otherwise every LLM tool call+fails with a TypeError.+"""-async def graph_explore(tools, entity: str, relation: str | None = None, depth: int = 1) -> dict:- """Explore relationships in the knowledge graph.+import logging- This is currently a placeholder. The final implementation should call the- knowledge graph store.- """- _LOG.info("graph_explore: entity=%s relation=%s depth=%d", entity, relation, depth)- # TODO: implement actual KG walk- from rag.advanced_rag.harness.tools.search import hybrid_search+# graph_explore is implemented alongside catalog/mindmap navigation because it+# reuses their outline-answering + evidence-pulling helpers.+from rag.advanced_rag.harness.tools.navigation import graph_explore # noqa: F401- query = f"{entity} {relation or ''}"- return await hybrid_search(tools, query=query.strip())+_LOG = logging.getLogger(__name__)-async def wiki_query(tools, topic: str) -> dict:+async def wiki_query(tools, query: str, keywords: str = "") -> dict:"""Query compiled wiki knowledge.This is currently a placeholder. The final implementation should call thecompiled wiki store."""- _LOG.info("wiki_query: topic=%s", topic)+ _LOG.info(f'[Wiki lookup] Looking up the compiled wiki for "{query}" (keywords: {keywords})')# TODO: implement actual wiki lookupfrom rag.advanced_rag.harness.tools.search import hybrid_search- return await hybrid_search(tools, query=topic)+ return await hybrid_search(tools, query=query, keywords=keywords)diff --git a/rag/advanced_rag/harness/tools/gating.py b/rag/advanced_rag/harness/tools/gating.pyindex 22ee3292a7..f0c231fe53 100644--- a/rag/advanced_rag/harness/tools/gating.py+++ b/rag/advanced_rag/harness/tools/gating.py@@ -10,9 +10,8 @@ SEARCH_PHASES = {"locate": {"goal": "Locate documents or regions that may contain the answer.","tools_priority": [- "toc_navigate",+ "catalog_navigate","mindmap_navigate",- "page_index_navigate","wiki_query","hybrid_search","bm25_search",@@ -24,7 +23,6 @@ SEARCH_PHASES = {"goal": "Explore deeply within the already located region.","tools_priority": ["hybrid_search",- "vector_search","bm25_search","graph_explore","inspector_open_context",@@ -74,7 +72,7 @@ def tool_fits_context(tool_name: str, context: OrchestratorContext) -> 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 == "toc_navigate" and not context.current_claim:+ if tool_name == "catalog_navigate" and not context.current_claim:return Falseif tool_name == "graph_explore" and not context.last_entity:return Falsediff --git a/rag/advanced_rag/harness/tools/navigation.py b/rag/advanced_rag/harness/tools/navigation.pyindex bb2ce25a9b..345ae64e24 100644--- a/rag/advanced_rag/harness/tools/navigation.py+++ b/rag/advanced_rag/harness/tools/navigation.py@@ -1,36 +1,607 @@-"""Navigation tools: TOC, page index, and mindmap."""+"""Navigation tools: document catalog and concept mindmap.+Both answer from a document's *compiled structure* rather than going straight to+retrieval: they read the compiled entities+relations for the documents in scope,+let the chat model answer from that outline, and pull the underlying chunks back+via each relevant entity's ``source_chunk_ids``.++Knowledge compilation writes every template kind into the same graph rows+(``{"entities": [...], "relations": [...]}``), so the two tools share one+implementation and differ only in which *kinds* they read:++* ``catalog_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+expansion and the keyword-sentence narrowing; without them navigation would hand+back full, un-narrowed chunks.+"""++import jsonimport logging+import re++import json_repair_LOG = logging.getLogger(__name__)+# Compiled-structure kinds that describe a document's *layout*: a tree/outline+# or a page index. ``_compilation_template_kind`` in the API folds page_index+# and knowledge_graph into "timeline"; RAPTOR is its own bucket and is+# inherently tree-like, so it counts too.+_CATALOG_KINDS = {"tree", "timeline", "raptor", "page_index", "pageindex"}++# Compiled-structure kinds that describe the document's *concepts*.+_MINDMAP_KINDS = {"mindmap", "mind_map"}++# Cap how much compiled structure we render into the prompt.+_MAX_ENTITIES = 300+_MAX_RELATIONS = 300+_MAX_EVIDENCE_CHUNKS = 24++_NAV_SYSTEM = """You are given {noun} of one or more documents — an outline of entities and their relations — and a question.++Decide whether that outline alone already answers the question.++Rules:+1. Answer ONLY from the outline below. Do not invent facts.+2. Set "is_sufficient" to true only when the outline genuinely answers the question; otherwise false with an empty answer.+3. Always fill "relevant_entities" with the exact `name` values of the entities most related to the question (up to 10), even when the outline is not sufficient — they are used to pull the underlying source text.++Output ONLY JSON, no prose, no code fences:+{{"is_sufficient": true/false, "answer": "<answer, or empty>", "relevant_entities": ["<entity name>", ...]}}"""+++def _normalize_kind(kind) -> str:+ """Mirror the API's kind normalization (page_index/knowledge_graph -> timeline)."""+ if not isinstance(kind, str):+ return ""+ normalized = kind.strip().lower().replace("-", "_")+ if normalized in {"pageindex", "page_index", "knowledge_graph"}:+ return "timeline"+ return normalized-async def toc_navigate(tools, topic: str, doc_scope: list[str] | None = None) -> dict:- """Locate by document table of contents.- Requires a KB with a compiled TOC artifact. This is currently a placeholder.- Replace it with the real implementation when the knowledge compilation TOC- tool is available. Falls back to hybrid search for now.+async def _load_compiled_structure(tools, doc_id: str, kinds: set) -> dict:+ """Read a document's compiled graphs for the given template ``kinds``.++ Mirrors the fetch in ``GET /datasets/<id>/documents/<doc_id>/structure/graph``:+ one query for the template-authored graph rows, a second for the RAPTOR row+ (which carries ``compile_kwd`` but no ``knowledge_graph_kwd``).++ Returns ``{"entities": [...], "relations": [...]}`` for the matching buckets."""- _LOG.info("toc_navigate called for topic=%s", topic)- # TODO: replace with actual TOC navigation when compilation layer is ready- # For now, fallback to hybrid search- from rag.advanced_rag.harness.tools.search import hybrid_search+ from common import settings+ from common.doc_store.doc_store_base import OrderByExpr+ from common.misc_utils import thread_pool_exec+ from rag.nlp import search++ resolved = await thread_pool_exec(tools._resolve_doc_tenant, doc_id)+ if not resolved:+ return {"entities": [], "relations": []}+ kb_id, tenant_id = resolved++ index_name = search.index_name(tenant_id)+ fields = [+ "content_with_weight",+ "compile_kwd",+ "compilation_template_ids",+ "compilation_template_kind_kwd",+ ]++ async def _query(condition: dict, limit: int) -> dict:+ try:+ res = await thread_pool_exec(+ settings.docStoreConn.search,+ fields,+ [],+ condition,+ [],+ OrderByExpr(),+ 0,+ limit,+ index_name,+ [kb_id],+ )+ return settings.docStoreConn.get_fields(res, fields) or {}+ except Exception:+ _LOG.exception("catalog_navigate: failed reading compiled structure for doc=%s", doc_id)+ return {}++ rows = dict(await _query({"doc_id": [doc_id], "knowledge_graph_kwd": ["graph"]}, 1000))+ rows.update(await _query({"doc_id": [doc_id], "compile_kwd": ["raptor_graph"]}, 16))++ entities: list[dict] = []+ relations: list[dict] = []+ for row in rows.values():+ try:+ graph = json.loads(row.get("content_with_weight") or "{}")+ except Exception:+ continue+ if not isinstance(graph, dict):+ continue++ compile_kwd = row.get("compile_kwd") or ""+ kind = _normalize_kind(row.get("compilation_template_kind_kwd") or compile_kwd)+ if compile_kwd == "raptor_graph":+ kind = "raptor"+ if kind not in kinds:+ continue++ entities.extend(graph.get("entities") or [])+ relations.extend(graph.get("relations") or [])++ return {"entities": entities, "relations": relations}+++def _render_structure(entities: list[dict], relations: list[dict]) -> str:+ """Render the compiled structure as a compact outline for the prompt."""+ lines: list[str] = []+ if entities:+ lines.append("Entities:")+ for e in entities[:_MAX_ENTITIES]:+ name = (e.get("name") or "").strip()+ if not name:+ continue+ typ = (e.get("type") or "other").strip()+ desc = " ".join((e.get("discription") or "").split())+ lines.append(f"- {name} ({typ})" + (f": {desc}" if desc else ""))+ if relations:+ lines.append("\nRelations:")+ for r in relations[:_MAX_RELATIONS]:+ src, tgt = (r.get("from") or "").strip(), (r.get("to") or "").strip()+ if not src or not tgt:+ continue+ lines.append(f"- {src} -[{(r.get('type') or 'related').strip()}]-> {tgt}")+ 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:+ return []+ from common import settings+ from common.doc_store.doc_store_base import OrderByExpr+ from common.misc_utils import thread_pool_exec+ from rag.nlp import search++ resolved = await thread_pool_exec(tools._resolve_doc_tenant, doc_id)+ if not resolved:+ return []+ kb_id, tenant_id = resolved++ fields = ["content_with_weight", "docnm_kwd", "doc_id"]+ try:+ res = await thread_pool_exec(+ settings.docStoreConn.search,+ fields,+ [],+ {"id": chunk_ids[:_MAX_EVIDENCE_CHUNKS]},+ [],+ OrderByExpr(),+ 0,+ _MAX_EVIDENCE_CHUNKS,+ search.index_name(tenant_id),+ [kb_id],+ )+ rows = settings.docStoreConn.get_fields(res, fields) or {}+ except Exception:+ _LOG.exception("catalog_navigate: failed loading evidence chunks for doc=%s", doc_id)+ return []++ chunks = []+ for cid, row in rows.items():+ chunks.append(+ {+ "chunk_id": cid,+ "content_with_weight": row.get("content_with_weight") or "",+ "docnm_kwd": row.get("docnm_kwd") or "",+ "doc_id": row.get("doc_id") or doc_id,+ }+ )+ return chunks+++def _doc_aggs(chunks: list[dict]) -> list[dict]:+ aggs, seen = [], set()+ for c in chunks:+ did = c.get("doc_id")+ if did and did not in seen:+ seen.add(did)+ aggs.append({"doc_id": did, "doc_name": c.get("docnm_kwd") or ""})+ return aggs+++async def _ask_structure(tools, topic: str, entities: list[dict], relations: list[dict], noun: str, label: str) -> tuple[str, list[str]]:+ """Ask the chat model to answer ``topic`` from the rendered outline.++ Returns ``(answer, relevant_entity_names)`` — ``answer`` is empty unless the+ model judged the outline sufficient; the names are always returned so the+ caller can pull the underlying source chunks.+ """+ verdict = {}+ try:+ from rag.prompts.generator import form_message, message_fit_in++ user = f"Question:\n{topic}\n\n{noun.capitalize()}:\n{_render_structure(entities, relations)}\n\nOutput JSON:"+ _, msg = message_fit_in(form_message(_NAV_SYSTEM.format(noun=f"the {noun}"), 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 {}+ if not isinstance(verdict, dict):+ verdict = {}+ except Exception:+ _LOG.exception(f"[{label}] Could not read the outline with the model.")++ is_sufficient = bool(verdict.get("is_sufficient"))+ answer = (verdict.get("answer") or "").strip() if is_sufficient else ""+ relevant = [n for n in (verdict.get("relevant_entities") or []) if isinstance(n, str)]+ _LOG.info(+ "[%s] The %s %s the question; %d relevant entity(ies): %s",+ label,+ noun,+ "answers" if is_sufficient else "does not fully answer",+ len(relevant),+ ", ".join(relevant[:10]) or "none",+ )+ return answer, relevant+++async def _navigate_compiled(+ 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.++ 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.++ :returns: ``{"answer": str, "chunks": [...], "doc_aggs": [...]}``+ """+ 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)++ 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)++ _LOG.info("[%s] Read an outline of %d entity(ies) and %d relation(s).", label, len(entities), len(relations))++ answer, relevant = await _ask_structure(tools, topic, entities, relations, noun, label)++ # 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)}+++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).++ :returns: ``{"answer": str, "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",+ )+++async def mindmap_navigate(tools, topic: str, keywords: str = "", doc_scope: list[str] | None = None) -> dict:+ """Answer from the documents' compiled concept mindmap.++ ``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": [...]}``+ """+ _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",+ )+++# ── Knowledge-graph exploration ─────────────────────────────────────────────+#+# Unlike catalog/mindmap (which read the merged "graph" JSON of one doc), the KG+# store keeps one searchable row per entity/relation, so graph_explore *searches*+# its way to a small subgraph: seed entities by the question, hop out over+# relations to the 2nd-degree neighbours, then answer from that subgraph.++_KG_SEEDS = 3 # entities matched directly to the question+_KG_HOPS = 1 # relation hops out from the seeds (1 => "2nd degree")+_KG_NEIGHBORS = 10 # neighbour entity rows resolved per hop+_KG_REL_LIMIT = 32 # relations fetched per endpoint filter+++async def _kg_scopes(tools, doc_scope: list[str] | None):+ """Resolve the (kb_id, tenant_id, doc_ids|None) groups to search.++ With a ``doc_scope`` the graph is limited to those docs (grouped by their+ KB); otherwise the whole bound KB graph is explored.+ """+ from common.misc_utils import thread_pool_exec++ if doc_scope:+ by_kb: dict[tuple, list[str]] = {}+ for doc_id in doc_scope:+ resolved = await thread_pool_exec(tools._resolve_doc_tenant, doc_id)+ if resolved:+ by_kb.setdefault(resolved, []).append(doc_id)+ return [(kb, tenant, docs) for (kb, tenant), docs in by_kb.items()]+ return [(kb.id, kb.tenant_id, None) for kb in getattr(tools, "kbs", []) or []]+++async def _kg_search(tools, kb_id: str, tenant_id: str, doc_ids, kind: str, text: str = "", top_n: int = 8, extra: dict | None = None) -> list[dict]:+ """Search the compiled KG rows of one KB and return the raw field maps."""+ from common import settings+ from common.doc_store.doc_store_base import MatchTextExpr, OrderByExpr+ from common.misc_utils import thread_pool_exec+ from rag.nlp import search++ condition: dict = {"knowledge_graph_kwd": [kind]}+ if doc_ids:+ condition["doc_id"] = list(doc_ids)+ if extra:+ condition.update(extra)++ fields = ["content_with_weight", "source_chunk_ids", "doc_id", "docnm_kwd", "from_entity_kwd", "to_entity_kwd"]+ exprs = []+ if text:+ if getattr(tools, "embed_mdl", None):+ try:+ exprs.append(await settings.retriever.get_vector(text, tools.embed_mdl, top_n, 0.1))+ except Exception:+ _LOG.exception("[Graph exploration] vector build failed; using keyword match")+ if not exprs:+ exprs.append(MatchTextExpr(["content_ltks", "content_sm_ltks"], text, top_n))++ try:+ res = await thread_pool_exec(+ settings.docStoreConn.search,+ fields,+ [],+ condition,+ exprs,+ OrderByExpr(),+ 0,+ top_n,+ search.index_name(tenant_id),+ [kb_id],+ )+ rows = settings.docStoreConn.get_fields(res, fields) or {}+ except Exception:+ _LOG.exception("[Graph exploration] KG search failed (kind=%s)", kind)+ return {}+ return rows+++def _kg_parse_entity(row: dict) -> dict | None:+ try:+ payload = json.loads(row.get("content_with_weight") or "{}")+ except Exception:+ payload = {}+ name = (payload.get("name") or payload.get("term") or payload.get("title") or "").strip()+ if not name:+ return None+ aliases = [str(a).strip() for a in (payload.get("aliases") or []) if str(a).strip()]+ return {+ "name": name,+ "type": (payload.get("type") or "other"),+ "discription": (payload.get("discription") or payload.get("description") or ""),+ "aliases": aliases,+ "source_chunk_ids": list(row.get("source_chunk_ids") or []),+ "doc_id": row.get("doc_id") or "",+ "docnm_kwd": row.get("docnm_kwd") or "",+ }+++def _kg_parse_relation(row: dict) -> dict | None:+ src = (row.get("from_entity_kwd") or "").strip()+ tgt = (row.get("to_entity_kwd") or "").strip()+ if not src or not tgt:+ return None+ typ = "related"+ try:+ payload = json.loads(row.get("content_with_weight") or "{}")+ typ = payload.get("type") or payload.get("relation") or "related"+ except Exception:+ pass+ return {+ "from": src,+ "to": tgt,+ "type": typ,+ "source_chunk_ids": list(row.get("source_chunk_ids") or []),+ "doc_id": row.get("doc_id") or "",+ }+++def _collect_evidence_ids(entities: list[dict], relations: list[dict], relevant_names: list[str]) -> dict:+ """Group the source_chunk_ids of the relevant entities AND relations by doc.++ An entity is relevant when its name/alias was named by the model; a relation+ is relevant when either endpoint is.+ """+ wanted = {n.strip().lower() for n in relevant_names if isinstance(n, str) and n.strip()}+ by_doc: dict[str, list[str]] = {}+ seen: set[tuple[str, str]] = set()++ def _add(doc_id: str, ids):+ for cid in ids or []:+ if not (isinstance(cid, str) and cid):+ continue+ key = (doc_id, cid)+ if key in seen:+ continue+ seen.add(key)+ by_doc.setdefault(doc_id, []).append(cid)++ for e in entities:+ names = {(e.get("name") or "").strip().lower(), *[(a or "").strip().lower() for a in (e.get("aliases") or [])]}+ if names & wanted:+ _add(e.get("doc_id") or "", e.get("source_chunk_ids"))+ for r in relations:+ if {(r.get("from") or "").strip().lower(), (r.get("to") or "").strip().lower()} & wanted:+ _add(r.get("doc_id") or "", r.get("source_chunk_ids"))+ return by_doc+++async def graph_explore(tools, query: str, keywords: str = "", doc_scope: list[str] | None = None) -> dict:+ """Explore the compiled knowledge graph to answer ``query``.++ Searches seed entities for the question, hops out over their relations to the+ 2nd-degree neighbours, asks the chat model to answer from that subgraph, then+ pulls the source passages behind the entities/relations it found relevant and+ narrows them with ``keywords``. Falls back to a plain hybrid search when the+ KB has no compiled graph or no source text is behind the relevant nodes.++ :returns: ``{"answer": str, "chunks": [...], "doc_aggs": [...]}``+ """+ from rag.advanced_rag.harness.tools.search import _narrow_by_keywords, hybrid_search++ _LOG.info(f'[Graph exploration] Exploring the knowledge graph for "{query}" (keywords: {keywords})')++ scopes = await _kg_scopes(tools, doc_scope)+ if not scopes:+ _LOG.info("[Graph exploration] No knowledge base in scope — falling back to a normal search.")+ return await hybrid_search(tools, query=query, keywords=keywords, doc_scope=doc_scope)++ text = f"{query} {keywords}".strip()+ entities: list[dict] = []+ relations: list[dict] = []+ ent_names: set[str] = set()++ def _add_entities(new: list[dict], scope_key: str = "") -> list[str]:+ added = []+ for e in new:+ key = f"{scope_key}:{e['name'].lower()}"+ if key in ent_names:+ continue+ ent_names.add(key)+ entities.append(e)+ added.append(e["name"])+ return added++ for kb_id, tenant_id, doc_ids in scopes:+ seed_rows = await _kg_search(tools, kb_id, tenant_id, doc_ids, "entity", text=text, top_n=_KG_SEEDS)+ seeds = [e for e in (_kg_parse_entity(r) for r in seed_rows.values()) if e]+ frontier = _add_entities(seeds, kb_id)+ _LOG.info("[Graph exploration] Seeded %d entity(ies): %s", len(frontier), ", ".join(frontier) or "none")++ for _hop in range(_KG_HOPS):+ if not frontier:+ break+ # Relations touching the current frontier (as source OR target).+ rel_rows: dict = {}+ rel_rows.update(await _kg_search(tools, kb_id, tenant_id, doc_ids, "relation", top_n=_KG_REL_LIMIT, extra={"from_entity_kwd": frontier}))+ rel_rows.update(await _kg_search(tools, kb_id, tenant_id, doc_ids, "relation", top_n=_KG_REL_LIMIT, extra={"to_entity_kwd": frontier}))+ hop_relations = [r for r in (_kg_parse_relation(x) for x in rel_rows.values()) if r]+ relations.extend(hop_relations)++ neighbour_names = {n for r in hop_relations for n in (r["from"], r["to"]) if n.lower() not in ent_names}+ if not neighbour_names:+ break+ neigh_rows = await _kg_search(tools, kb_id, tenant_id, doc_ids, "entity", text=" ".join(neighbour_names), top_n=_KG_NEIGHBORS)+ wanted = {n.lower() for n in neighbour_names}+ neighbours = [e for e in (_kg_parse_entity(r) for r in neigh_rows.values()) if e and e["name"].lower() in wanted]+ frontier = _add_entities(neighbours, kb_id)+ _LOG.info("[Graph exploration] Hop %d reached %d neighbour entity(ies).", _hop + 1, len(frontier))- return await hybrid_search(tools, query=topic, doc_scope=doc_scope)+ if not entities and not relations:+ _LOG.info("[Graph exploration] No compiled knowledge graph here — falling back to a normal search.")+ return await hybrid_search(tools, query=query, keywords=keywords, doc_scope=doc_scope)+ _LOG.info("[Graph exploration] Built a subgraph of %d entity(ies) and %d relation(s).", len(entities), len(relations))-async def page_index_navigate(tools, topic: str, kb_ids: list[str] | None = None) -> dict:- """Navigate by page index."""- _LOG.info("page_index_navigate called for topic=%s", topic)- from rag.advanced_rag.harness.tools.search import hybrid_search+ answer, relevant = await _ask_structure(tools, query, entities, relations, "knowledge graph", "Graph exploration")- return await hybrid_search(tools, query=topic, kb_ids=kb_ids)+ evidence = _collect_evidence_ids(entities, relations, relevant)+ chunks: list[dict] = []+ for doc_id, ids in evidence.items():+ if doc_id and ids:+ chunks.extend(await _load_chunks_by_ids(tools, doc_id, ids))+ if not chunks:+ _LOG.info("[Graph exploration] No source text behind those nodes — falling back to a normal search.")+ fallback = await hybrid_search(tools, query=query, keywords=keywords, doc_scope=doc_scope)+ fallback["answer"] = answer+ return fallback-async def mindmap_navigate(tools, concept: str, kb_ids: list[str] | None = None) -> dict:- """Locate by concept mindmap."""- _LOG.info("mindmap_navigate called for concept=%s", concept)- from rag.advanced_rag.harness.tools.search import hybrid_search+ before = len(chunks)+ chunks = _narrow_by_keywords(chunks, keywords)+ _LOG.info("[Graph exploration] Pulled %d source passage(s) behind those nodes, kept %d after keyword filtering.", before, len(chunks))- return await hybrid_search(tools, query=concept, kb_ids=kb_ids)+ return {"answer": answer, "chunks": chunks, "doc_aggs": _doc_aggs(chunks)}diff --git a/rag/advanced_rag/harness/tools/registry.py b/rag/advanced_rag/harness/tools/registry.pyindex 072e0b2ba0..74bcb2db73 100644--- a/rag/advanced_rag/harness/tools/registry.py+++ b/rag/advanced_rag/harness/tools/registry.py@@ -60,7 +60,8 @@ def _navigate_schema(name: str, desc: str) -> dict:"parameters": {"type": "object","properties": {- "topic": {"type": "string", "description": "navigate by topic"},+ "topic": {"type": "string", "description": "the topic to navigate to."},+ "keywords": {"type": "string", "description": "the keywords used for searching split by space or ','."},},"required": ["topic"],},diff --git a/rag/advanced_rag/harness/tools/search.py b/rag/advanced_rag/harness/tools/search.pyindex 4014cf190c..351cbba44c 100644--- a/rag/advanced_rag/harness/tools/search.py+++ b/rag/advanced_rag/harness/tools/search.py@@ -129,8 +129,8 @@ def _narrow_by_keywords(chunks: list[dict], keywords: str) -> list[dict]:if len(kwds) < 3:kwds = [k.strip().lower() for k in (keywords or "").split(" ") if k.strip()]_kwds = []- for i in range(len(kwds)-1):- _kwds.append(kwds[i] + " "+ kwds[i+1])+ for i in range(len(kwds) - 1):+ _kwds.append(kwds[i] + " " + kwds[i + 1])kwds = _kwdsscored = [(ck, _narrow_content(ck.get("content_with_weight") or ck.get("content") or "", kwds)) for ck in chunks]@@ -150,6 +150,20 @@ def _narrow_by_keywords(chunks: list[dict], keywords: str) -> list[dict]:return out+def _search_cache_key(effective_query: str, target_ids, top_n: int, doc_scope) -> tuple:+ """Key a retrieval by what actually determines its result.++ Includes the scope/limits so semantically different searches are never+ collapsed together — only a genuinely identical query is served from cache.+ """+ return (+ " ".join((effective_query or "").split()).lower(),+ tuple(sorted(target_ids or ())),+ int(top_n),+ tuple(sorted(doc_scope or ())),+ )++def _normalize(kbinfos: dict, tenant_ids: list[str] | str | None) -> dict:if not kbinfos:return {"chunks": [], "doc_aggs": []}@@ -169,12 +183,22 @@ async def hybrid_search(tools, query: str, kb_ids: list[str] | None = None, top_if not tools.kb_ids and not kb_ids:return {"chunks": [], "doc_aggs": []}target_ids = kb_ids or tools.kb_ids- _LOG.info(f"[Hybrid search]: {query} -> {keywords}")+ _LOG.info(f'[Hybrid search] Searching the knowledge base for "{query}" (keywords: {keywords})')# Query expansion: append the formalized-question keywords + close synonyms# so hybrid/BM25 retrieval gets extra recall signal.effective_query = f"{query} {keywords}".strip() if keywords else query+ # Per-request dedup: an identical query+scope is retrieved at most once, so+ # e.g. pre_search and a claim search asking the same question don't repeat+ # the ES round-trip, child fetch and narrowing.+ cache = getattr(tools, "search_cache", None)+ cache_key = _search_cache_key(effective_query, target_ids, top_n, doc_scope)+ if cache is not None and cache_key in cache:+ cached = cache[cache_key]+ _LOG.info(f"[Hybrid search] Already searched this — reusing the {len(cached.get('chunks', []))} passage(s) found earlier.")+ return cached+embd_mdl = tools.embed_mdlvector_weight = 0.3 if embd_mdl else 0@@ -195,7 +219,9 @@ async def hybrid_search(tools, query: str, kb_ids: list[str] | None = None, top_if keywords:length = len(kbinfos["chunks"])kbinfos["chunks"] = _narrow_by_keywords(kbinfos.get("chunks", []), keywords)- _LOG.info(f"[Hybrid search]({keywords}): snippet {length} -> {len(kbinfos['chunks'])}")+ _LOG.info(f"[Hybrid search] Kept {len(kbinfos['chunks'])} of {length} passage(s) that actually mention the keywords.")+ if cache is not None:+ cache[cache_key] = kbinfosreturn kbinfos@@ -204,7 +230,7 @@ async def vector_search(tools, query: str, kb_ids: list[str] | None = None, top__LOG.warning("vector_search: no embed_mdl available")return {"chunks": [], "doc_aggs": []}- _LOG.info(f"[Vector search]: {query} -> {keywords}")+ _LOG.info(f'[Vector search] Searching by meaning for "{query}" (keywords: {keywords})')effective_query = f"{query} {keywords}".strip() if keywords else querytarget_ids = kb_ids or tools.kb_idskbinfos = await settings.retriever.retrieval(@@ -219,15 +245,16 @@ async def vector_search(tools, query: str, kb_ids: list[str] | None = None, top_aggs=False,highlight=False,)+ kbinfos = _normalize(kbinfos, tools.tenant_ids)if keywords:length = len(kbinfos["chunks"])kbinfos["chunks"] = _narrow_by_keywords(kbinfos.get("chunks", []), keywords)- _LOG.info(f"[Vector search]({keywords}): snippet {length} -> {len(kbinfos['chunks'])}")- return _normalize(kbinfos, tools.tenant_ids)+ _LOG.info(f"[Vector search] Kept {len(kbinfos['chunks'])} of {length} passage(s) that actually mention the keywords.")+ return kbinfosasync def bm25_search(tools, query: str, kb_ids: list[str] | None = None, top_n: int = 12, keywords: str = "") -> dict:- _LOG.info(f"[BM25 search]: {query} -> {keywords}")+ _LOG.info(f'[BM25 search] Searching by keyword for "{query}" (keywords: {keywords})')target_ids = kb_ids or tools.kb_idseffective_query = f"{query} {keywords}".strip() if keywords else querykbinfos = await settings.retriever.retrieval(@@ -242,18 +269,19 @@ async def bm25_search(tools, query: str, kb_ids: list[str] | None = None, top_n:aggs=False,highlight=False,)+ kbinfos = _normalize(kbinfos, tools.tenant_ids)if keywords:length = len(kbinfos["chunks"])kbinfos["chunks"] = _narrow_by_keywords(kbinfos.get("chunks", []), keywords)- _LOG.info(f"[BM25 search]({keywords}): snippet {length} -> {len(kbinfos['chunks'])}")- return _normalize(kbinfos, tools.tenant_ids)+ _LOG.info(f"[BM25 search] Kept {len(kbinfos['chunks'])} of {length} passage(s) that actually mention the keywords.")+ return kbinfosasync def web_search(tools, query: str, keywords: str = "") -> dict:if not tools.has_web():return {"chunks": [], "doc_aggs": []}- _LOG.info(f"[Web search]: {query} -> {keywords}")+ _LOG.info(f'[Web search] Searching the web for "{query}"')try:from common.misc_utils import thread_pool_exec@@ -265,8 +293,14 @@ async def web_search(tools, query: str, keywords: str = "") -> dict:return {"chunks": [], "doc_aggs": []}-async def structured_query(tools, question: str, kb_ids: list[str] | None = None) -> dict:- _LOG.info(f"[Structured search]: {question}")+async def structured_query(tools, query: str, keywords: str = "", kb_ids: list[str] | None = None) -> dict:+ """Answer from the structured (tabular) KBs by translating the query to SQL.++ ``keywords`` is accepted for schema conformance but deliberately unused: the+ query is translated to SQL rather than keyword-matched, and the rows it+ returns are not prose to narrow.+ """+ _LOG.info(f'[Structured search] Querying the structured (table) data for "{query}"')sql_kbs = [kb for kb in tools.sql_kbs if kb_ids is None or kb.id in kb_ids]if not sql_kbs:return {"answer": "", "chunks": [], "doc_aggs": []}@@ -275,7 +309,7 @@ async def structured_query(tools, question: str, kb_ids: list[str] | None = Nonetenant_id = sql_kbs[0].tenant_idsql_kb_ids = [kb.id for kb in sql_kbs]try:- ans = await use_sql(question, tools.field_map, tenant_id, tools.chat_mdl, quota=True, kb_ids=sql_kb_ids)+ ans = await use_sql(query, tools.field_map, tenant_id, tools.chat_mdl, quota=True, kb_ids=sql_kb_ids)except Exception:_LOG.exception("structured_query failed")return {"answer": "", "chunks": [], "doc_aggs": []}diff --git a/rag/advanced_rag/think_log.py b/rag/advanced_rag/think_log.pyindex 87790501b3..5c6461fe23 100644--- a/rag/advanced_rag/think_log.py+++ b/rag/advanced_rag/think_log.py@@ -17,11 +17,14 @@"""Surface selected internal INFO logs to the client as ``<think>`` content.During an agentic ``rag_agent`` turn we attach a context-scoped logging sink so-the pipeline's bracket-tagged progress logs — ``[agentic-rag]``,-``[formalize_question]``, ``[pre_search]``, ``[Planner]``, ``[orchestrator]``,-``[agentic]``, ``[Hybrid search]``, ``[BM25 search]``, ``[Web search]``,-``[ToolLoop]``, ``[FunctionTool]`` … — can be streamed to the front end as-reasoning without instrumenting every call site.+the pipeline's bracket-tagged progress logs — ``[Agentic RAG]``,+``[Formalizing the question]``, ``[Preliminary search]``, ``[Planner]``,+``[Orchestrator]``, ``[Agentic research]``, ``[Hybrid search]``,+``[BM25 search]``, ``[Web search]``, ``[Composing the answer]``,+``[Tool loop]``, ``[Function tool]`` … — can be streamed to the front end as+reasoning without instrumenting every call site. The tags double as+human-readable stage labels, so the same message serves the backend log and+the user-facing thinking stream.The sink is stored in a :class:`contextvars.ContextVar`, so only the async tasktree of the current request (which inherits the context) forwards its logs —diff --git a/rag/llm/chat_model.py b/rag/llm/chat_model.pyindex 9a9161a416..59a792c84a 100644--- a/rag/llm/chat_model.py+++ b/rag/llm/chat_model.py@@ -593,7 +593,7 @@ class Base(ABC):try:for _round in range(self.max_rounds + 1):reasoning_start = False- logging.info(f"[ToolLoop] round={_round} model={self.model_name} tools={[t['function']['name'] for t in tools]}")+ logging.info(f"[Tool loop] Deciding what to do next (step {_round + 1}); available tools: {', '.join(t['function']['name'] for t in tools)}")response = await self.async_client.chat.completions.create(model=self.model_name, messages=history, stream=True, tools=tools, tool_choice="auto", **gen_conf, **extra_request_kwargs@@ -653,7 +653,7 @@ class Base(ABC):_commit_round(round_usage, round_estimate)if answer and not final_tool_calls:- logging.info(f"[ToolLoop] round={_round} completed with text response, exiting")+ logging.info(f"[Tool loop] Answering directly at step {_round + 1} — no tool needed.")yield total_tokensreturn@@ -673,13 +673,13 @@ class Base(ABC):return tc, name, {}, None, etcs = list(final_tool_calls.values())- logging.info(f"[ToolLoop] round={_round} executing {len(tcs)} tool(s): {[tc.function.name for tc in tcs]}")+ logging.info(f"[Tool loop] Step {_round + 1}: running {', '.join(tc.function.name for tc in tcs)}...")for tc in tcs:try:args = json_repair.loads(tc.function.arguments)except Exception:args = {}- yield f"<think>Executing {tc.function.name} with args: {tc.function.arguments}</think>"+ yield f"<think>Running the {tc.function.name} tool...</think>"results = await asyncio.gather(*[_exec_tool(tc) for tc in tcs])# Terminal-tool short-circuit: stream a terminal tool's@@ -688,7 +688,7 @@ class Base(ABC):if _terminal:for tc, name, args, result, err in results:if name in _terminal and not err:- logging.info(f"[ToolLoop] terminal tool {name!r} called; streaming result and stopping")+ logging.info(f"[Tool loop] The {name} tool produced the final answer — done.")out = result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)if out:yield out@@ -2043,7 +2043,7 @@ class LiteLLMBase(ABC):for _round in range(self.max_rounds + 1):reasoning_start = Falsereasoning_content = ""- logging.info(f"[ToolLoop] round={_round} model={self.model_name} tools={[t['function']['name'] for t in tools]}")+ logging.info(f"[Tool loop] Deciding what to do next (step {_round + 1}); available tools: {', '.join(t['function']['name'] for t in tools)}")completion_args = self._construct_completion_args(history=history, stream=True, tools=True, **gen_conf)# Request authoritative usage on the final streaming chunk.@@ -2110,7 +2110,7 @@ class LiteLLMBase(ABC):_commit_round(round_usage, round_estimate)if answer and not final_tool_calls:- logging.info(f"[ToolLoop] round={_round} completed with text response, exiting")+ logging.info(f"[Tool loop] Answering directly at step {_round + 1} — no tool needed.")yield total_tokensreturn@@ -2130,13 +2130,13 @@ class LiteLLMBase(ABC):return tc, name, {}, None, etcs = list(final_tool_calls.values())- logging.info(f"[ToolLoop] round={_round} executing {len(tcs)} tool(s): {[tc.function.name for tc in tcs]}")+ logging.info(f"[Tool loop] Step {_round + 1}: running {', '.join(tc.function.name for tc in tcs)}...")for tc in tcs:try:args = json_repair.loads(tc.function.arguments)except Exception:args = {}- yield f"<think>Executing {tc.function.name} with args: {tc.function.arguments}</think>"+ yield f"<think>Running the {tc.function.name} tool...</think>"results = await asyncio.gather(*[_exec_tool(tc) for tc in tcs])# Terminal-tool short-circuit: a terminal tool already@@ -2146,7 +2146,7 @@ class LiteLLMBase(ABC):if _terminal:for tc, name, args, result, err in results:if name in _terminal and not err:- logging.info(f"[ToolLoop] terminal tool {name!r} called; streaming result and stopping")+ logging.info(f"[Tool loop] The {name} tool produced the final answer — done.")out = result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)if out:yield outdiff --git a/rag/llm/tool_decorator.py b/rag/llm/tool_decorator.pyindex 3f1a421eb0..be8b4ea4c1 100644--- a/rag/llm/tool_decorator.py+++ b/rag/llm/tool_decorator.py@@ -319,7 +319,7 @@ class FunctionToolSession:f"Tool arguments for {name} must be an object, got {type(arguments).__name__}")fn = self.tools_map[name]- logging.info(f"[FunctionTool] invoke name={name} args={str(arguments)[:200]}")+ logging.info(f"[Function tool] Running the {name} tool with: {str(arguments)[:200]}")if asyncio.iscoroutinefunction(fn):coro = fn(**arguments)else: