""" rag_agent.py — Agentic RAG via a smolagents manager + search sub-agent. Architecture (manager / sub-agent): * MANAGER — a ToolCallingAgent that ANALYZES the user's question (intent, meaning, keywords) instead of literally pasting it into a search, then decomposes it into 1-3 focused search tasks and delegates each one to the `knowledge_searcher` sub-agent. It never queries the knowledge base directly — it only reasons and directs. * SUB-AGENT (`knowledge_searcher`) — a ToolCallingAgent holding ONLY the `retriever` tool. Given a focused task from the manager, it runs the retriever SEVERAL times, deliberately rephrasing the query on every iteration (synonyms, reordering, narrowing/broadening) so it never repeats the same search wording, then returns a findings report with source tags. This replaces the older single-agent design (one agent holding the retriever tool and deciding on its own) — which tended to paste the user's whole verbatim sentence into `retriever`, producing noisy semantic matches. IMPORTANT CAVEAT: tool-calling reliability still depends heavily on the underlying model. `google/gemma-4-E2B-it` (the app's default LLM) is small enough that the manager may delegate poorly or the sub-agent may call `retriever` in a malformed way. If agentic RAG Chat seems to ignore the knowledge base, switch to a larger model (e.g. Gemma-4-E4B or above). """ import re import threading import types from typing import Optional from agents import agent_streaming from agents.agent_factory import build_smol_agent from backend import model_registry as mr from backend import models from backend.knowledge_base import ( DocumentSummaryTool, KeyPointsTool, ListTopicsTool, MindMapTool, RetrieverTool, SubthemeSummaryTool, ThemeSummaryTool, VisualRetrieverTool, reset_visual_tool_hits, ) from ui import i18n _rag_agent = None _rag_agent_model_id = None _rag_agent_theme = "" _rag_agent_subtheme = "" _rag_agent_sources = [] _rag_agent_max_steps = 6 _rag_agent_searcher_max_steps = None _rag_agent_execution_timeout = None _rag_agent_n_ctx = None _rag_agent_visual_retrieval = False _rag_tool = None _rag_visual_tool = None _rag_summary_tools = [] _rag_agent_lock = threading.Lock() # ────────────────────────────────────────────────────────────────── # Sub-agent identity (required by smolagents' managed_agents machinery). # ────────────────────────────────────────────────────────────────── SEARCHER_AGENT_NAME = "knowledge_searcher" SEARCHER_AGENT_DESCRIPTION = ( "Runs focused semantic searches over document text in the user's indexed knowledge base " "and returns a findings report with source tags. Call with task='search query keywords' " "(e.g. knowledge_searcher(task='contract summary')). Describe WHAT to look for. " "Never call for listing themes/topics — use list_knowledge_base_topics directly instead." ) # The manager's VISUAL-INDEX RULE paragraph. It is appended to # STRICT_SYSTEM_INSTRUCTIONS ONLY when RAG visual retrieval is enabled — # the rule teaches the manager to delegate scanned/image-heavy docs to the # searcher's `visual_retriever` tool, which does not exist when the toggle # is OFF (offering a rule for a tool the agent can never call wastes steps). RAG_MANAGER_VISUAL_RULE = ( "VISUAL-INDEX RULE (scanned / image-heavy documents):\n" "- A summarization tool's output may mark a source as having page images in the visual index ('🖼️ Page images available in the visual index'), or the extracted text may be unreadable OCR (e.g. `(cid:123)` fragments). Both mean the document's REAL content lives in its PAGE IMAGES — the text chunks are unreliable.\n" "- In that case DO NOT conclude the knowledge base lacks information and DO NOT answer from the garbled text alone. DELEGATE to `knowledge_searcher` with an explicit task: 'use `visual_retriever` to search the page images for (e.g. the document's title, date, issuer, key clauses)' and tell it to report what the PAGE IMAGES show. The retrieved pages are then read by the multimodal grounding pass.\n" "- For summaries of scanned documents, ALWAYS add such a `knowledge_searcher` visual task before writing the final answer — the visual pages are the authoritative source.\n\n" ) # ────────────────────────────────────────────────────────────────── # Strict grounding — layer 1: agent-level system instructions (applied # once, at agent construction, if this smolagents version supports it). # ────────────────────────────────────────────────────────────────── STRICT_SYSTEM_INSTRUCTIONS = ( "You are a retrieval research manager. You answer the user's question " "using ONLY the user's own indexed knowledge base — never your own " "general knowledge or training data, even if you believe you know the " "answer.\n\n" "Available tools to you as the manager:\n" "- `knowledge_searcher`: sub-agent that executes semantic searches over document text.\n" "- `list_knowledge_base_topics`: lists all indexed themes, subthemes, and filenames directly from metadata.\n" "- `summarize_theme`: produces a comprehensive summary of a specific theme.\n" "- `summarize_subtheme`: produces a summary of a specific subtheme under a theme.\n" "- `summarize_document`: produces a summary of a specific document by its source filename.\n" "- `find_key_points`: extracts top takeaways/highlights for a theme, subtheme, or document.\n" "- `create_mind_map`: generates a concept tree or Mermaid diagram outline of topics.\n\n" "METADATA VS SEMANTIC SEARCH RULE:\n" "- Themes, subthemes, and filenames are METADATA. NEVER delegate metadata queries (like 'what themes exist', 'list subthemes', or 'available files') to `knowledge_searcher` — use `list_knowledge_base_topics` directly instead.\n" "- When the user asks for a summary, overview, or highlights of a theme, subtheme, or document, call the corresponding summarization tool (`summarize_theme`, `summarize_subtheme`, `summarize_document`, `find_key_points`) directly to obtain the full structured outline. If deeper details on specific sub-topics are needed, you may also run focused searches via `knowledge_searcher`.\n" "- For questions about factual information, facts, or concepts inside documents, analyze the question and delegate focused keyword search tasks to `knowledge_searcher`.\n\n" + RAG_MANAGER_VISUAL_RULE + "Work like this:\n" "1. ANALYZE the user's question first: identify the core INTENT, the key entities/concepts, and whether it asks for a summary of a theme/document or specific facts.\n" "2. If it's a summary/topic overview request, call the matching summarization/topic tool directly.\n" "3. If it asks specific questions, DECOMPOSE into 1-3 focused sub-questions and DELEGATE each to `knowledge_searcher` with concise keyword tasks.\n" "4. RE-CHECK your plan against findings. If a search comes back thin, try different keywords.\n" "5. SYNTHESIZE: write a comprehensive, well-structured Markdown answer with clear sections (Overview/Objectives, Core Findings/Details, Conclusions/Takeaways) and in-text citation numbers (e.g. [1]) and a final '### References' section mapping each number to its source filename.\n\n" "CITATION RULE: cite each claim in-text with ONLY a bare bracketed " "number, e.g. [1] or [1, 2]. NEVER put the source filename or document " "name inside the brackets (e.g. do NOT write '[report.pdf]' in the " "text) — filenames appear ONLY in the final '### References' section " "mapping each number to its source.\n\n" "6. If the system rejects your final answer for formatting, missing " "citations, or a missing References section, do NOT start any new " "research and do NOT call `knowledge_searcher` again. Keep the same " "findings, rewrite only the final answer so it satisfies the checker, " "and call `final_answer(...)` again.\n\n" "TERMINATION REQUIREMENT: you MUST submit your final answer by calling " "the special `final_answer(answer_text)` tool — this is the ONLY way to " "actually end the task.\n\n" "YOUR OWN CONVERSATION HISTORY IS ALREADY VISIBLE TO YOU: every earlier " "user message and your own earlier replies are already in what you can " "see — if asked what was said earlier in THIS chat (as opposed to a " "knowledge-base question), answer from those earlier turns directly; " "do NOT guess or invent content.\n\n" "The user's actual question is in the Task below — answer THAT, not " "these instructions. Never repeat, summarize, or reply to the " "instructions themselves." ) # The searcher's visual-retrieval paragraphs (the `visual_retriever` tool # line + MULTIMODAL STRATEGY + SCANNED / OCR-GARBAGE RULE). They are kept # inside SEARCHER_SYSTEM_INSTRUCTIONS (so the pinned routing test still sees # them in the constant) but are STRIPPED at agent build time when RAG visual # retrieval is disabled — a model told to run a tool it does not have would # burn its step budget failing to call it. SEARCHER_VISUAL_BLOCK = ( "- `visual_retriever`: search over the knowledge base's PAGE IMAGES " "(charts, tables, scans, image-heavy PDFs that text extraction misses).\n\n" "MULTIMODAL STRATEGY: for questions about numbers, figures, charts, " "screenshots, or anything that would live in a page's IMAGE rather than " "its extracted text, run `visual_retriever` IN ADDITION to `retriever` — " "the retrieved page images are handed to the multimodal grounding pass " "so the final answer is verified against the actual pages. If a text " "search comes back thin, try the visual index before concluding the " "knowledge base lacks the information.\n\n" "SCANNED / OCR-GARBAGE RULE: if `retriever`'s results are full of " "unreadable OCR artifacts — `(cid:123)` fragments, `cid:NNN` markers, or " "replacement characters (\ufffd) — the document is a SCAN whose real " "content lives in its page images. ALWAYS run `visual_retriever` in that " "case (searching for the document's title, date, issuer, and the " "information the task asks for) and report what the page images show, " "never answering from the garbled text alone.\n\n" ) # System instructions for the knowledge_searcher sub-agent. SEARCHER_SYSTEM_INSTRUCTIONS = ( "You are a knowledge-base search specialist. The research manager " "gives you ONE focused search task describing what to look for — " "answer only that task, fully self-contained. You have NO memory of " "any other call made to you.\n\n" "Your tools:\n" "- `retriever`: semantic search over the knowledge base's TEXT chunks.\n" "- `visual_retriever`: search over the knowledge base's PAGE IMAGES " "(charts, tables, scans, image-heavy PDFs that text extraction misses).\n\n" "MULTIMODAL STRATEGY: for questions about numbers, figures, charts, " "screenshots, or anything that would live in a page's IMAGE rather than " "its extracted text, run `visual_retriever` IN ADDITION to `retriever` — " "the retrieved page images are handed to the multimodal grounding pass " "so the final answer is verified against the actual pages. If a text " "search comes back thin, try the visual index before concluding the " "knowledge base lacks the information.\n\n" "SCANNED / OCR-GARBAGE RULE: if `retriever`'s results are full of " "unreadable OCR artifacts — `(cid:123)` fragments, `cid:NNN` markers, or " "replacement characters (\ufffd) — the document is a SCAN whose real " "content lives in its page images. ALWAYS run `visual_retriever` in that " "case (searching for the document's title, date, issuer, and the " "information the task asks for) and report what the page images show, " "never answering from the garbled text alone.\n\n" "NEGATIVE GUARD: Themes, subthemes, and file names are metadata attributes, " "not document body text. Never search for queries like 'available themes', " "'list of subthemes', or 'list of documents' — search only for factual concepts " "and information described in the documents.\n\n" "SEARCH STRATEGY — DIVERSIFY EVERY QUERY:\n" "1. Extract the essential keywords from the task (drop filler words).\n" "2. Run `retriever` with a keyword-focused query FIRST.\n" "3. Then run 1-3 MORE searches, each with a DIFFERENT formulation than " "the previous one:\n" " - a paraphrase using synonyms,\n" " - the same terms in a different order,\n" " - a narrower query focused on a single entity/aspect,\n" " - a broader query if the narrow ones return nothing.\n" " NEVER call `retriever` twice with the same query string.\n" "4. Stop once you have enough evidence, or after about 4 varied " "searches.\n\n" "REPORT: return a concise findings report listing what you found, " "tagging each item with its source filename (e.g. 'report.pdf'). If " "nothing relevant was found, say so plainly — do not invent or guess." ) # Visual-free variants of the two instruction sets — built ONCE at import # time by stripping the visual blocks above. `_build_searcher_agent` / # `_build_manager_agent` use these when RAG visual retrieval is DISABLED # (the default), so the agents are never taught to use the `visual_retriever` # tool (which they also never receive). STRICT_SYSTEM_INSTRUCTIONS_NO_VISUAL = STRICT_SYSTEM_INSTRUCTIONS.replace( RAG_MANAGER_VISUAL_RULE, "" ) SEARCHER_SYSTEM_INSTRUCTIONS_NO_VISUAL = SEARCHER_SYSTEM_INSTRUCTIONS.replace( SEARCHER_VISUAL_BLOCK, "" ) # ────────────────────────────────────────────────────────────────── # Strict grounding — layer 2: per-question task template (applied every # call, in chat.py, via build_strict_task()). # ────────────────────────────────────────────────────────────────── def _scope_display(value) -> str: """Render a metadata scope value as a readable comma-joined string. The RAG tab sends theme/subtheme selections as ARRAYS (multi-select), so a value arrives as either a single string (backward-compatible callers) or a list. A list must never be stringified directly — `str()` / f-string interpolation would leak the Python list notation into the agent's prompt (the old `Active Theme: '['ditctab2019d5_en']'`).""" if value is None: return "" if isinstance(value, str): vals = [value.strip()] else: vals = [str(v).strip() for v in value if v is not None and str(v).strip()] return ", ".join(v for v in vals if v) def build_strict_task(question: str, lang_key: str = "kh", theme: str = "", subtheme: str = "", sources: Optional[list] = None) -> str: """Wrap the user's question with explicit strict-grounding instructions and the current active filter scope (theme/subtheme/sources).""" scope_lines = [] theme_disp = _scope_display(theme) if theme_disp: scope_lines.append(f"Active Theme: {theme_disp}") subtheme_disp = _scope_display(subtheme) if subtheme_disp: scope_lines.append(f"Active Subtheme: {subtheme_disp}") if sources: clean_srcs = [str(s) for s in sources if s] if clean_srcs: scope_lines.append(f"Active Sources: {', '.join(clean_srcs)}") scope_block = "" if scope_lines: scope_block = ( "--- Filter Scope in Knowledge Base ---\n" + "\n".join(scope_lines) + "\n(If the user says 'this theme', 'this subtheme', or 'this document', refer to the active scope above)\n\n" ) return ( i18n._output_lang_instruction(lang_key) + scope_block + "Answer the user's question using ONLY information retrieved " "from the indexed knowledge base. Do not use your own general " "knowledge, and do not guess.\n\n" "1. ANALYZE the question: identify whether it asks for an overview/summary " "of a theme/document or specific factual answers.\n" "2. If the user asks for a summary, overview, topics, key points, or a mind map " "of a theme/subtheme/document, call the corresponding tool directly " "(`summarize_theme`, `summarize_subtheme`, `summarize_document`, " "`find_key_points`, `create_mind_map`, `list_knowledge_base_topics`).\n" "3. For factual questions, break into 1-3 sub-questions and call `knowledge_searcher` " "with concise keyword search tasks.\n" "4. If a search task returns thin results, try different keywords — never repeat the same task.\n" "5. Write a comprehensive, well-structured Markdown answer with in-text citation numbers (e.g. [1], [2]) " "and a '### References' section mapping each number to its source filename.\n" "6. Submit your answer by calling `final_answer(answer_text)`. NEVER output your internal plan, list of tools to use, or problem analysis in final_answer — provide ONLY the factual response directly.\n" "7. If the knowledge base has nothing relevant, state clearly that " "the knowledge base doesn't contain this information — do not guess.\n\n" + i18n._task_conciseness_directive(lang_key) + "\n\n---\n" "The user's question is:\n" f"{question}" ) # ────────────────────────────────────────────────────────────────── # Strict grounding — layer 3: post-hoc verification. Doesn't rely on the # model actually obeying the instructions above, NOR on introspecting # smolagents' internal step/memory structure (which varies across # versions and previously caused false "never searched" verdicts even # when the retriever clearly ran and returned real results — see the # CodeAgent transcript where `Out: Retrieved documents (sources: ...)` # was printed but the old introspection still reported called=False). # # Instead, the RetrieverTool instance itself tracks how many times it # was called and how many of those calls found something (see # knowledge_base.RetrieverTool) — reset before each run, read after. # ────────────────────────────────────────────────────────────────── def never_searched_message(lang_key: str = "kh") -> str: """Bilingual guard message: the agent completed WITHOUT calling the retriever (call_count == 0). Rendered in the UI language so a Khmer UI never shows an English answer.""" return ( "⚠️ ខ្ញុំមិនបានស្វែងរកក្នុងមូលដ្ឋានចំណេះដឹងសម្រាប់សំណួរនេះ ដូច្នេះខ្ញុំមិនឆ្លើយទេ — " "សូមព្យាយាមបកស្រាយសំណួររបស់អ្នកឡើងវិញ។" if lang_key == "kh" else "⚠️ I didn't search the knowledge base for this, so I'm not answering — " "please try rephrasing your question." ) def nothing_found_message(lang_key: str = "kh") -> str: """Bilingual guard message: the agent searched but found nothing relevant (found_count == 0). Rendered in the UI language so a Khmer UI never shows an English answer.""" return ( "⚠️ ខ្ញុំបានស្វែងរកក្នុងមូលដ្ឋានចំណេះដឹងរួចហើយ ប៉ុន្តែរកមិនឃើញអ្វីដែលពាក់ព័ន្ធនឹង " "សំណួរនេះទេ ដូច្នេះខ្ញុំនឹងមិនទាយវិញទេ។ សូមព្យាយាមបកស្រាយសំណួរ ឬបញ្ចូលឯកសារដែល " "គ្របដណ្តប់លើប្រធានបទនេះជាមុនសិន។" if lang_key == "kh" else "⚠️ I searched the indexed knowledge base but found nothing relevant to " "this question, so I won't guess. Try rephrasing, or index a document " "that covers this topic first." ) def reset_retriever_stats(): """Call right before agent.run() so this run's stats start from zero.""" if _rag_tool is not None: _rag_tool.reset_stats() if _rag_visual_tool is not None: _rag_visual_tool.reset_stats() for tool in _rag_summary_tools: if hasattr(tool, "reset_stats"): tool.reset_stats() # Clear any page images a PREVIOUS run's visual_retriever tool calls # stashed — this run's grounding pass must only see THIS run's pages. reset_visual_tool_hits() def get_retriever_stats() -> tuple: """Call right after agent.run() returns. Returns (call_count, found_count, sources_used) across the retriever plus any RAG summary tools used this run. `sources_used` is the ACTUAL set of source filenames the tools returned this run, tracked directly by the tools themselves rather than trusting the model's own in-text citations.""" tools = ([_rag_tool] if _rag_tool is not None else []) + \ ([_rag_visual_tool] if _rag_visual_tool is not None else []) + \ list(_rag_summary_tools) call_count = 0 found_count = 0 sources_used = set() for tool in tools: if tool is None: continue call_count += int(getattr(tool, "call_count", 0) or 0) found_count += int(getattr(tool, "found_count", 0) or 0) sources_used.update(set(getattr(tool, "sources_used", set()) or set())) return call_count, found_count, sources_used def get_visual_retriever_stats() -> tuple: """(call_count, found_count, pages_found) for JUST the visual_retriever tool — the signal the chat footer uses to say "the agent actually pulled page images this run", separate from get_retriever_stats()'s aggregate (which mixes the text retriever, the visual tool, and the summary tools). pages_found is the total number of page images actually decoded across the run's successful calls. (0, 0, 0) when the visual tool was never built.""" if _rag_visual_tool is None: return 0, 0, 0 return (int(getattr(_rag_visual_tool, "call_count", 0) or 0), int(getattr(_rag_visual_tool, "found_count", 0) or 0), int(getattr(_rag_visual_tool, "pages_found", 0) or 0)) def normalize_in_text_citations(answer: str, refs) -> str: """Rewrite model-emitted in-text citations that carry the SOURCE NAME (filename, URL, or page title) inside brackets OR parentheses (e.g. '[CV Sample 1 - Data Scientist AI Specialist.pdf]', '[https://en.wikipedia.org/wiki/2026_FIFA_World_Cup]', or '(CV Sample 1 - Data Scientist AI Specialist.pdf)') into the numbered form '[N]' / '(N)' that the verified References list uses. Local GGUF models frequently ignore the "cite with a bracketed NUMBER" instruction and paste the whole retrieved filename into the citation marker instead. `renumber_citations` (general_agent.py) only remaps [digits] brackets, so a [filename] / (filename) marker previously leaked through into the rendered answer verbatim. chat.py runs this AFTER renumber_citations and passes the RENUMBERED refs, so each marker whose name matches a verified reference (case-insensitive substring, either direction — same matching rule as extract_verified_references) is replaced by that reference's FINAL sequential number — keeping parenthesized markers in sync with the renumbered References list. Markers that match NO verified source are left untouched (they are not citations). Note: a model-written numbered paren like `(3)` passes the digit guard below and is left alone — renumber_citations only remaps [digits] brackets, so such a paren is preserved verbatim rather than renumbered (a deliberate, conservative choice: digits in parens are common in ordinary prose). The parenthesized form is deliberately stricter than the bracketed one: parentheses are common in ordinary prose (e.g. "(Core AI Engineering)", "(see figure 2)"), so a parenthesized marker is only treated as a citation when its content actually LOOKS like a filename (carries a real file extension) AND matches a verified source — a bare title mention like '(Sample 1)' stays prose. `refs` is a list of (number, name) or (number, name1, name2) tuples: the [(number, source_name)] shape from extract_verified_references() (RAG — filename sources), or the [(number, title, url)] shape renumber_citations returns for web sources (Deep Research / General agentic — page-title AND URL). Every name in each tuple is matched, so a bracket containing EITHER the page title OR the raw URL resolves to that source's number. """ if not answer or not refs: return answer def _replace(match, open_ch, close_ch, require_ext): inner = (match.group(1) or "").strip() # Empty or already-numbered markers ([1], [1, 2], (1), (1, 2)) are # left for renumber_citations to handle (or drop) — the filename # scan below must never touch them. if not inner or re.fullmatch(r"\d+(?:\s*,\s*\d+)*", inner): return match.group(0) # Only attempt a filename match on marker content that actually # LOOKS like a filename — a bare '.pdf'-style extension or a long # fragment. Without this guard, a source named 'report.pdf' would # rewrite a legitimate prose '[pdf]' or '[report]' mention into a # citation number (false positive). The model's real output always # carries the full 'Name.pdf' form, which both gates below accept. if require_ext: # Parenthesized markers need a real file extension (e.g. # '.pdf', '.docx') before they are even candidate citations — # parens are prose-frequent, so a bare title mention like # '(Sample 1)' must never match. if not re.search(r"\.[A-Za-z0-9]{2,8}\b", inner): return match.group(0) elif "." not in inner and len(inner) < 8: return match.group(0) low = inner.lower() for ref in refs: num = ref[0] # Match against EVERY name in the ref: (num, name) for # filename sources, (num, title, url) for web sources — so a # bracket containing the page title OR the raw URL both # resolve to the same number. for name in ref[1:]: name_low = str(name or "").lower() if name_low and (low in name_low or name_low in low): return f"{open_ch}{num}{close_ch}" return match.group(0) # Bracketed citations: [filename] -> [N]. answer = re.sub(r"\[([^\[\]]+)\]", lambda m: _replace(m, "[", "]", require_ext=False), answer) # Parenthesized citations: (filename) -> (N), with the stricter # extension guard above. answer = re.sub(r"\(([^()]+)\)", lambda m: _replace(m, "(", ")", require_ext=True), answer) return answer def extract_verified_references(answer: str, sources_used) -> list: """Parse the model's own numbered '### References' section (e.g. '[1] report.pdf', '1. report.pdf') and keep only entries whose filename was ACTUALLY retrieved this run (cross-checked against sources_used from RetrieverTool) — so chat.py can render a numbered References list whose [n] tags match the model's in-text citations, without trusting the model to have invented sources. Mirrors general_agent.resolve_actually_used_sources(): the model's in-text numbers are preserved as written, so an answer citing '[1]' in the body lines up with '[1] report.pdf' in the list below. Falls back to numbering the actually-retrieved sources_used (in sorted order) when the model wrote no parseable/valid references. """ if not sources_used: return [] header_match = re.search(r"#{1,6}\s*(references?|ឯកសារយោង)\b", answer or "", re.IGNORECASE) if header_match: section = (answer or "")[header_match.end():] entries = [] seen = set() for line in section.splitlines(): line = line.strip() m = re.match(r"^\[?(\d+)\]?[.:\-)]?\s*(.+)$", line) if not m: continue num = int(m.group(1)) name = m.group(2).strip().strip("[]").strip() if not name or name in seen: continue matched = next((s for s in sources_used if name.lower() in s.lower() or s.lower() in name.lower()), None) if matched and matched not in seen: entries.append((num, matched)) seen.add(matched) if entries: return sorted(entries, key=lambda e: e[0]) return [(i + 1, name) for i, name in enumerate(sorted(sources_used))] RAG_AGENT_DEFAULT_MAX_STEPS = 6 SEARCHER_DEFAULT_MAX_STEPS = 5 # Deep-research-style re-planning: every N manager steps it stops and # re-reads what the sub-agent has found so far, so it can revise its # search plan instead of blindly executing the initial one (same # mechanism deep_research_agent.py uses — this is what makes a research # loop "deep" rather than a single-pass agentic chat). RAG_PLANNING_INTERVAL = 3 # final_answer_checks validator thresholds: # * reject an answer too short to be a real grounded report # The verified References block is appended by chat.py from the actual # tracked sources, so the validator no longer rejects missing refs. MIN_FINAL_REPORT_CHARS = 150 _RAG_REFERENCES_RE = re.compile(r'#{1,6}\s*(references?|ឯកសារយោង)\b', re.IGNORECASE) def _validate_final_report(final_answer, *_, **__) -> bool: """`final_answer_checks` validator for the RAG manager. Raises an actionable Exception on rejection — smolagents surfaces the message back to the model as feedback for its next step (see deep_research_agent._validate_final_report for the same pattern).""" text = str(final_answer or "").strip() if len(text) < MIN_FINAL_REPORT_CHARS: raise ValueError( f"Your final answer is only {len(text)} character(s) — too " f"short to be a real grounded answer (need at least " f"{MIN_FINAL_REPORT_CHARS}). Write a complete Markdown " "answer (a short introduction, a clearly-headed section per " "sub-question you searched, and a brief conclusion), then " "call final_answer(report_text) again with the FULL answer " "text as the argument." ) return True def _scaled_max_steps(model_id: str, default_max_steps: int) -> int: """Larger/slower local GGUF models pay a much higher per-step cost when a parsing loop goes wrong, so their step budget is scaled down to fail fast instead of grinding through the full default (same reasoning as model_registry.get_max_steps_for_model).""" return mr.get_max_steps_for_model(model_id, default_max_steps) # The max-steps hand-off transcript cap for the `knowledge_searcher` # sub-agent — its findings are verbatim retrieval chunk texts (wordier than # the Data worker's compact tables), so it gets the same larger cap as the # Deep Research search agent. _SEARCHER_OBS_TRANSCRIPT_CAP = 12000 def _searcher_max_steps_handoff(self, task): """The `knowledge_searcher`'s max-steps fallback (instance-patched onto the agent in `_build_searcher_agent`): prefer the run's REAL retrieved findings — the verbatim retriever tool observations (the chunk texts the manager needs to ground its answer) — over smolagents' stock last-ditch raw-text answer, so the manager receives what the agent actually found instead of a leaked channel marker / envelope / code fence. Thin wrapper over the shared agent_streaming.max_steps_findings_handoff (the same helper the Data `data_worker` and Deep Research `web_search_agent` use). NEVER raises.""" return agent_streaming.max_steps_findings_handoff( self, task, cap=_SEARCHER_OBS_TRANSCRIPT_CAP) def _build_searcher_agent(llm, tool: RetrieverTool, visual_tool: Optional[VisualRetrieverTool] = None, model_id: str = "", max_steps: Optional[int] = None, execution_timeout: Optional[int] = None, use_tool_calling: bool = True, n_ctx: Optional[int] = None): """Build the `knowledge_searcher` sub-agent: holds the TEXT retriever tool PLUS the `visual_retriever` page-image tool (when a visual index capability is available), and is deliberately told to diversify its query wording on every search iteration. Registered as a managed_agents entry on the manager, so smolagents exposes it to the manager as a callable tool.""" if max_steps is None: max_steps = _scaled_max_steps(model_id, SEARCHER_DEFAULT_MAX_STEPS) instructions = (SEARCHER_SYSTEM_INSTRUCTIONS if visual_tool is not None else SEARCHER_SYSTEM_INSTRUCTIONS_NO_VISUAL) if n_ctx and n_ctx > 0: instructions += ( f"\n\nCONTEXT BUDGET: Your effective context window is ~{n_ctx} tokens. " "Keep searches concise and stop once you have sufficient evidence to answer " "so observations do not overflow the context." ) agent_tools = [tool] if visual_tool is not None: agent_tools.append(visual_tool) agent = build_smol_agent( llm, tools=agent_tools, max_steps=max_steps, execution_timeout=execution_timeout, use_tool_calling=use_tool_calling, instructions=instructions, extra_kwargs={ "name": SEARCHER_AGENT_NAME, "description": SEARCHER_AGENT_DESCRIPTION, "provide_run_summary": True, }, ) # Max-steps hand-off (see agent_streaming.max_steps_findings_handoff): # when the sub-agent burns its whole step budget without emitting a real # final answer (the Muse Glimmer runs shipped a leaked `Calling tools:` # envelope / code fence as its "answer"), the manager would receive that # garbage — losing the retrieved chunks it needs to ground the reply. # Deliver the run's verbatim retriever observations (the chunk texts) # instead. Same instance-level patch as the Data `data_worker` and the # Deep Research `web_search_agent`; the RAG MANAGER keeps the stock # behavior (its observations are the managed-agent report wrapper, not # raw findings). try: agent._orig_handle_max_steps_reached = agent._handle_max_steps_reached agent._handle_max_steps_reached = types.MethodType( _searcher_max_steps_handoff, agent ) except Exception: pass print(f"[RAGAgent] Building {type(agent).__name__} sub-agent " f"'{SEARCHER_AGENT_NAME}' on '{model_id or '(shared)'}' …") return agent def _build_manager_agent(llm, searcher, model_id: str = "", summary_tools=None, max_steps: Optional[int] = None, execution_timeout: Optional[int] = None, use_tool_calling: bool = True, visual_retrieval: bool = True): """Build the manager agent. It holds NO search tool of its own — only the managed `knowledge_searcher` sub-agent (plus smolagents' auto-added final_answer tool). Its whole job is to analyze the user's question, split it into focused search tasks, delegate them, and synthesize the grounded answer. `visual_retrieval=False` drops the VISUAL-INDEX RULE from the instructions (the rule points at a `visual_retriever` tool that does not exist when it is disabled).""" if max_steps is None: max_steps = _scaled_max_steps(model_id, RAG_AGENT_DEFAULT_MAX_STEPS) agent = build_smol_agent( llm, tools=list(summary_tools or []), max_steps=max_steps, execution_timeout=execution_timeout, use_tool_calling=use_tool_calling, instructions=(STRICT_SYSTEM_INSTRUCTIONS if visual_retrieval else STRICT_SYSTEM_INSTRUCTIONS_NO_VISUAL), # Deep-research strategy: re-plan every few steps instead of # blindly executing the initial search plan, and return a concise # run summary so the manager can see what the sub-agent found. # final_answer_checks is attached only when this smolagents # version's __init__ accepts it (optional_kwargs guard). extra_kwargs={ "managed_agents": [searcher], # Per-model override: models flagged planning-incompatible # (Muse Glimmer — it echo-loops the re-plan prompt) get None # (planning off), everyone else keeps the default interval. "planning_interval": mr.planning_interval_for_model(model_id, RAG_PLANNING_INTERVAL), "provide_run_summary": True, }, optional_kwargs={"final_answer_checks": [_validate_final_report]}, ) print(f"[RAGAgent] Building {type(agent).__name__} manager on " f"'{model_id or '(shared)'}' …") return agent def get_rag_agent(model_id: Optional[str] = None, theme: str = "", subtheme: str = "", max_steps: Optional[int] = None, searcher_max_steps: Optional[int] = None, execution_timeout: Optional[int] = None, use_tool_calling: bool = True, provider: Optional[str] = None, n_ctx: Optional[int] = None, sources: Optional[list] = None, visual_retrieval: bool = False): """Lazily build (or rebuild) the manager + `knowledge_searcher` sub-agent. `use_tool_calling` requests native tool-calling (ToolCallingAgent); auto-falls-back to CodeAgent if the loaded model doesn't support it. `searcher_max_steps` (optional): the `knowledge_searcher` sub-agent's own step budget (the manager's is `max_steps`) — the UI's per-tab agentic step controls for RAG (see AgentControls.svelte). None uses the model-scaled default (SEARCHER_DEFAULT_MAX_STEPS). Included in the cache key, so changing it rebuilds the pair. `execution_timeout` (optional): the per-step Python code-executor timeout in seconds (the RAG "Exec timeout" control in agentic mode) — threaded to build_smol_agent's executor_kwargs. None = AUTO (the factory default). Included in the cache key, so changing it rebuilds. `n_ctx` (optional): the RAG tab's context window, threaded to models.get_llm() so a per-tab n_ctx change rebuilds this agent with the freshly (re)loaded model. Included in the cache key for that reason. `visual_retrieval` (default False): the RAG tab's "Visual Retriever + VLM" toggle. When OFF, the `visual_retriever` page-image tool is NOT attached to the `knowledge_searcher` sub-agent and the visual instructions (VISUAL-INDEX RULE / SCANNED rule) are stripped from both agents' system prompts, so the agentic RAG path never touches page images or loads the retriever/VLM. Included in the cache key so toggling it rebuilds the pair. """ global _rag_agent, _rag_agent_model_id, _rag_agent_theme, _rag_agent_subtheme global _rag_agent_max_steps, _rag_agent_searcher_max_steps, _rag_agent_execution_timeout, _rag_tool global _rag_summary_tools, _rag_agent_n_ctx, _rag_agent_sources, _rag_visual_tool global _rag_agent_visual_retrieval target = model_id or models._llm_model_id sources = list(sources or []) _same_run = ( target == _rag_agent_model_id and theme == _rag_agent_theme and subtheme == _rag_agent_subtheme and max_steps == _rag_agent_max_steps and searcher_max_steps == _rag_agent_searcher_max_steps and execution_timeout == _rag_agent_execution_timeout and n_ctx == _rag_agent_n_ctx and sources == _rag_agent_sources and visual_retrieval == _rag_agent_visual_retrieval ) if _rag_agent is not None and _same_run: return _rag_agent with _rag_agent_lock: if _rag_agent is not None and _same_run: return _rag_agent # `provider` is threaded through (same as general_agent) so a # non-default provider requested from the RAG tab actually takes # effect; get_llm treats provider=None as the default. llm = models.get_llm(target, provider=provider, n_ctx=n_ctx) # The tool-calling decision (ToolCallingAgent vs CodeAgent fallback) # is owned by build_smol_agent via the shared default predicate # `supports_native_tool_calls` — same as general_agent. Passing the # raw flag here means the factory applies the predicate itself. _rag_tool = RetrieverTool(theme=theme, subtheme=subtheme, sources=sources) # The visual page-image tool — the second retrieval tool the # `knowledge_searcher` sub-agent can use (charts / scans / pages # that text extraction misses). OFFERED ONLY when the RAG tab's # "Visual Retriever + VLM" toggle is ON (default OFF — visual # retrieval is resource-intensive: it can pull in the 2-8 GB # retriever model and the VLM grounding pass). When disabled the # tool is None, so `_build_searcher_agent` neither attaches it nor # teaches its use, and VLM grounding is also skipped in chat.py. _rag_visual_tool = VisualRetrieverTool() if visual_retrieval else None # The summary/listing tools ALSO receive the RAG tab's selected # sources — a summary, key-points, mind-map or topic listing must # never cover documents outside the user's selected files, exactly # like the retriever already scopes factual searches (the file # filter is otherwise silently ignored by the summary path). _rag_summary_tools = [ ListTopicsTool(sources=sources), ThemeSummaryTool(sources=sources), SubthemeSummaryTool(sources=sources), DocumentSummaryTool(sources=sources), KeyPointsTool(sources=sources), MindMapTool(sources=sources), ] _searcher = _build_searcher_agent(llm, _rag_tool, _rag_visual_tool, target, searcher_max_steps, execution_timeout, use_tool_calling=use_tool_calling, n_ctx=n_ctx) _rag_agent = _build_manager_agent(llm, _searcher, target, _rag_summary_tools, max_steps, execution_timeout, use_tool_calling=use_tool_calling, visual_retrieval=visual_retrieval) _rag_agent_model_id = target _rag_agent_theme = theme _rag_agent_subtheme = subtheme _rag_agent_sources = sources _rag_agent_max_steps = max_steps _rag_agent_searcher_max_steps = searcher_max_steps _rag_agent_execution_timeout = execution_timeout _rag_agent_n_ctx = n_ctx _rag_agent_visual_retrieval = visual_retrieval # Standard smolagents behaviour: a freshly-built agent starts # with empty memory. See agent_memory.py's module docstring for # why this app no longer tries to restore memory from a previous # model or app session. tc_label = type(_rag_agent).__name__ print(f"[RAGAgent] Built {tc_label} manager + {SEARCHER_AGENT_NAME} on '{target}' …") return _rag_agent def reset_agent(): """Drop the cached CodeAgent wrapper (does NOT unload the underlying LLM itself — that's shared/managed by models.get_llm()). Call this whenever the RAG-tab model changes or the LLM is force-reloaded/unloaded elsewhere, so this agent doesn't keep holding a stale model reference. """ global _rag_agent, _rag_agent_model_id, _rag_agent_theme, _rag_agent_subtheme global _rag_agent_max_steps, _rag_agent_searcher_max_steps, _rag_agent_execution_timeout, _rag_tool global _rag_summary_tools, _rag_agent_n_ctx, _rag_agent_sources, _rag_visual_tool _rag_agent = None _rag_agent_model_id = None _rag_agent_theme = "" _rag_agent_subtheme = "" _rag_agent_sources = [] _rag_agent_max_steps = 6 _rag_agent_searcher_max_steps = None _rag_agent_execution_timeout = None _rag_agent_n_ctx = None _rag_tool = None _rag_visual_tool = None _rag_summary_tools = []