""" general_agent.py — Agentic General Chat via a smolagents agent (CodeAgent or ToolCallingAgent — see agents/agent_factory.py for the choice), using smolagents' own built-in tools (see: https://huggingface.co/docs/smolagents/tutorials/tools) instead of any app-specific tool like RAG Chat's RetrieverTool (knowledge_base.py) or Data Analysis's install_package (data_analysis.py). Tools used here: - DuckDuckGoSearchTool — live web search - VisitWebpageTool — fetch + read a page's full text when a search snippet isn't enough - SpeechToTextTool — transcribes an audio file/URL to text (see https://huggingface.co/docs/smolagents/en/reference/default_tools#smolagents.SpeechToTextTool). Useful if the user's message references a local audio file path or URL they want transcribed. NOTE: this is a separate, simpler code path from the app's own dedicated 🎙️ Speech to Text tab (models.py's transcribe_audio()) — it downloads and lazily loads its own fixed Whisper checkpoint (openai/whisper-large-v3-turbo) the first time the agent actually calls it, is not configurable from the model dropdowns, and doesn't chunk long (>30s) audio or force a language the way models.py's pipeline does. For serious/long transcription work, point the user at the dedicated STT tab instead; this tool is meant for the agent to handle short ad-hoc audio incidentally mentioned mid-conversation. PythonInterpreterTool is deliberately NOT added: it's only meaningful for ToolCallingAgent (JSON-style tool calls). CodeAgent already writes and executes its own Python for every step, so adding PythonInterpreterTool as a *tool* on top of that would just be a redundant, confusing entry in the agent's toolbox. Same caveat as rag_agent.py / data_analysis.py: tool-calling reliability depends heavily on the underlying model. Gemma-4-E2B (this app's default) may never call a tool at all, or call it malformed, and just hallucinate an answer from its own knowledge instead. If the agent seems to ignore the web tools, switch to a larger model (Gemma-4-E4B+, or any capable GGUF model) in the LLM dropdown first. """ import os import re import threading import time from pathlib import Path from typing import Optional from smolagents import DuckDuckGoSearchTool, Tool, VisitWebpageTool from agents.agent_factory import build_smol_agent from backend import model_registry as mr from backend import models from ui import i18n _general_agent = None _general_agent_model_id = None _general_agent_max_steps = None _general_agent_execution_timeout = None _general_agent_lang_key = None _general_agent_n_ctx = None _general_agent_lock = threading.Lock() # ────────────────────────────────────────────────────────────────── # Citation tracking — DuckDuckGoSearchTool / VisitWebpageTool are # smolagents' own built-in tools, not app-specific ones we can add # call-count/found-count bookkeeping to by editing their source. Instead, # thin subclasses record every query run / URL actually opened, mirroring # knowledge_base.RetrieverTool's self-tracked call_count/found_count # pattern (see rag_agent.py's strict-grounding verification for why: it's # more reliable than trying to introspect the agent's internal # step/memory structure, which varies across smolagents versions). # # This lets chat.py append a guaranteed-accurate "sources consulted this # turn" list after every agentic run, independent of whether the model # actually remembered to write its own in-text citations/References # section (which — like RAG's strict grounding — depends on the # underlying model's instruction-following and can't be fully trusted). # ────────────────────────────────────────────────────────────────── # smolagents' DuckDuckGoSearchTool formats each hit as a markdown link # followed by its snippet, e.g. "[Page Title](https://example.com/page)\n # some snippet text…", under a "## Search Results" header. This pulls the # real (title, url) pairs straight out of that text so chat.py can cite an # actual clickable source instead of just repeating the query string (a # query the model typed is not itself a source — see the "did not provide # the actual link" issue this fixes). _MARKDOWN_LINK_RE = re.compile(r'\[([^\]]+)\]\((https?://[^\s\)]+)\)') # Matches the "### References" (or similar) heading GENERAL_AGENT_INSTRUCTIONS # asks the model to end its answer with, so the section body can be pulled # out and parsed for the URLs the model actually claims it used. _REFERENCES_HEADER_RE = re.compile(r'#{1,6}\s*references?\b', re.IGNORECASE) _BARE_URL_RE = re.compile(r'https?://\S+') def extract_model_cited_urls(answer: str) -> list: """Pull (num_str, title, url) tuples out of the model's own '### References' section at the end of its answer. Tolerates both formats the model might use: - '[1] Page Title — https://example.com/page' - '[Page Title](https://example.com/page)' or '[1] [Page Title](https://example.com/page)' Returns a list of (num_str, title, url) tuples, where num_str is the citation index tag (e.g. "1", "7") if present, or None if omitted. """ if not answer: return [] header_match = _REFERENCES_HEADER_RE.search(answer) if not header_match: return [] section = answer[header_match.end():] items = [] seen_urls = set() for line in section.splitlines(): line = line.strip() if not line: continue url_match = _BARE_URL_RE.search(line) if not url_match: # Check for pure markdown link format [Title](https://...) md_match = _MARKDOWN_LINK_RE.search(line) if md_match: title, url = md_match.group(1), md_match.group(2) url = url.strip().rstrip(').,;') if url not in seen_urls: prefix = line[:md_match.start()].strip() num_m = re.match(r'^\[?(\d+)\]?[.\-:)]*\s*', prefix) num_str = num_m.group(1) if num_m else None items.append((num_str, title.strip(), url)) seen_urls.add(url) continue url = url_match.group(0).rstrip(').,;') if url in seen_urls: continue prefix = line[:url_match.start()].strip() num_m = re.match(r'^\[?(\d+)\]?[.\-:)]*\s*', prefix) num_str = num_m.group(1) if num_m else None title = re.sub(r'^\[?\d+\]?[.\-:)]*\s*', '', prefix).strip(' -—:') items.append((num_str, title or url, url)) seen_urls.add(url) return items def resolve_actually_used_sources(answer: str, urls_visited: list, result_links: list) -> list: """Return the (num_str, title, url) tuples that should be shown as this turn's actually-used references — the INTERSECTION of what the model claims it cited (its own '### References' section) and what was REALLY searched/visited this run. """ known_title_by_url = {} for u in urls_visited: known_title_by_url.setdefault(u, u) for title, u in result_links: known_title_by_url.setdefault(u, title) cited = extract_model_cited_urls(answer) used, seen = [], set() fallback_idx = 1 for num, title, url in cited: real_url = url if url in known_title_by_url else next( (k for k in known_title_by_url if k.rstrip('/') == url.rstrip('/')), None ) if real_url and real_url not in seen: item_num = num if num else str(fallback_idx) used.append((item_num, title or known_title_by_url[real_url], real_url)) seen.add(real_url) fallback_idx += 1 if used: return used if urls_visited: return [(str(i + 1), u, u) for i, u in enumerate(urls_visited) if u not in seen] return [(str(i + 1), title, url) for i, (title, url) in enumerate(result_links)] def strip_trailing_references_section(answer: str) -> str: """Cut off the model's own '### References' section (if present) from the end of its answer, so chat.py can replace it with the verified list from resolve_actually_used_sources() instead of showing both the model's (unverified, possibly incomplete/hallucinated) version and a second, accurate one back to back. """ if not answer: return answer header_match = _REFERENCES_HEADER_RE.search(answer) if not header_match: return answer return answer[:header_match.start()].rstrip() def renumber_citations(answer: str, used_sources: list) -> tuple: """Remap citation numbers in `answer` (e.g. [2, 3, 7] -> [1, 2, 3]) and in `used_sources` so that citations start sequentially from 1 to N without gaps. Prevents citation hallucinations: - If `used_sources` is empty (no tools called or all model-cited URLs were hallucinated), any stray bracketed citation tags like [1], [2] are stripped from the answer text. - Any in-text citation tag referencing an unverified source index (not present in `used_sources`) is removed from the answer text. Returns (renumbered_answer, renumbered_sources). """ if not answer: return answer, used_sources if not used_sources: # No verified sources exist for this run — strip any stray/hallucinated [n] tags from text cleaned_answer = re.sub(r'\s*\[\d+(?:\s*,\s*\d+)*\]', '', answer) return cleaned_answer, [] num_map = {} renumbered_sources = [] for new_idx, item in enumerate(used_sources, 1): if len(item) == 3: old_num, title, url = item else: old_num, title, url = str(new_idx), item[0], item[1] new_num_str = str(new_idx) if old_num: num_map[str(old_num)] = new_num_str renumbered_sources.append((new_num_str, title, url)) def replace_bracket(match): content = match.group(1) parts = [p.strip() for p in content.split(',')] if all(p.isdigit() for p in parts if p): # Only keep numbers that mapped to a verified source in num_map! valid_parts = [num_map[p] for p in parts if p in num_map] if not valid_parts: return "" # Remove the bracket entirely if all numbers inside were hallucinated seen = set() dedup = [] for np in valid_parts: if np not in seen: dedup.append(np) seen.add(np) return "[" + ", ".join(dedup) + "]" return match.group(0) renumbered_answer = re.sub(r'\[(\d+(?:\s*,\s*\d+)*)\]', replace_bracket, answer) # Clean up double spaces created by removed brackets renumbered_answer = re.sub(r' +', ' ', renumbered_answer) return renumbered_answer, renumbered_sources class TrackedDuckDuckGoSearchTool(DuckDuckGoSearchTool): input_aliases = { "query": ("q", "question", "search", "search_query", "keywords", "task", "text", "prompt"), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queries_run = [] # Real (title, url) pairs actually surfaced by a search this run — # see _MARKDOWN_LINK_RE above. Deduplicated in insertion order. self.result_links = [] self._last_call_time = 0.0 def forward(self, query: str) -> str: # Guard against a model looping on the EXACT same query — seen in # practice with some larger local GGUF models, which will re-run # an identical search 5-6+ times in a row instead of noticing it # already has the results (each call still costs a real network # round-trip). Case/whitespace-insensitive match; a genuinely # different/refined query is still allowed through normally. normalized = query.strip().lower() if normalized and any(normalized == q.strip().lower() for q in self.queries_run): return ( f"You already searched for '{query}' earlier in this run and " "got results — running the exact same query again will only " "return the same thing. Stop searching and write your final " "answer using what you already found, or search for something " "MEANINGFULLY DIFFERENT if you still need more information." ) # Inter-search pacing: delay at least 1.2s between rapid searches # to prevent DuckDuckGo rate-limiting. now = time.time() elapsed = now - self._last_call_time if elapsed < 1.2 and self._last_call_time > 0: time.sleep(1.2 - elapsed) self.queries_run.append(query) result = None try: result = super().forward(query) except Exception as e: err_str = str(e).lower() if "ratelimit" in err_str or "202" in err_str or "too many requests" in err_str: # Retry once after 2.0s backoff time.sleep(2.0) try: result = super().forward(query) except Exception as retry_e: return f"DuckDuckGo search rate-limited: {retry_e}. Use existing information or try again later." else: return f"DuckDuckGo search error: {e}" finally: self._last_call_time = time.time() for title, url in _MARKDOWN_LINK_RE.findall(result or ""): pair = (title.strip(), url.strip()) if pair not in self.result_links: self.result_links.append(pair) return result _IMAGE_EXFILTRATION_RE = re.compile(r"!\[(.*?)\]\((https?://[^\s)]+)\)") def sanitize_scraped_markdown(text: str) -> str: """Sanitize scraped web markdown to neutralize remote markdown image tags, which can be exploited in indirect prompt injection attacks for data exfiltration.""" if not text: return "" return _IMAGE_EXFILTRATION_RE.sub(r"[image: \1]", text) class TrackedVisitWebpageTool(VisitWebpageTool): input_aliases = { "url": ("link", "webpage", "page", "address", "site", "target"), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.urls_visited = [] def forward(self, url: str) -> str: self.urls_visited.append(url) content = super().forward(url) return sanitize_scraped_markdown(content) # ────────────────────────────────────────────────────────────────── # File I/O tools — ReadFileTool and WriteFileTool give the agent the # ability to read from and write to files on disk within the app's # workspace root. Paths outside the workspace root are rejected. # ────────────────────────────────────────────────────────────────── _FILE_TOOL_ROOT: Path = Path( os.environ.get("FILE_TOOL_ROOT", str(Path(__file__).parent.parent)) ).resolve() _MAX_READ_BYTES = 1_000_000 # 1 MB safety cap for read_file _PROTECTED_READ_FILENAMES = {".env", "user_config.json"} _BLOCKED_WRITE_EXTENSIONS = { ".py", ".pyw", ".pyc", ".pyd", ".exe", ".bat", ".cmd", ".ps1", ".psm1", ".vbs", ".vbe", ".wsf", ".wsh", ".dll", ".sys", ".so", ".dylib", ".sh", ".bash", } _PROTECTED_WRITE_DIRS = {"backend", "agents", "ui", "installer", "tools", ".git", ".venv", ".venv-build"} def _safe_resolve(raw_path: str, for_write: bool = False) -> Path: """Resolve `raw_path` under _FILE_TOOL_ROOT; raises ValueError if the resolved path escapes the root (path traversal protection) or touches protected sensitive system files or source directories.""" cleaned = (raw_path or "").strip().strip('"').strip("'") if not cleaned: raise ValueError("Empty file path provided.") p = (_FILE_TOOL_ROOT / cleaned).resolve() try: rel = p.relative_to(_FILE_TOOL_ROOT) except ValueError: raise ValueError( f"Path '{raw_path}' resolves to '{p}', which is outside the " f"allowed workspace root '{_FILE_TOOL_ROOT}'. " "Only paths within the workspace root are permitted." ) parts = rel.parts filename = p.name.lower() ext = p.suffix.lower() if not for_write: if filename in _PROTECTED_READ_FILENAMES or filename.endswith(".env"): raise ValueError(f"Access denied: reading secret or credential file '{filename}' is restricted.") if any(part in (".git", ".venv", ".venv-build") for part in parts): raise ValueError(f"Access denied: reading internal directory '{parts[0]}' is restricted.") if for_write: if filename in _PROTECTED_READ_FILENAMES or filename.endswith(".env"): raise ValueError(f"Access denied: writing to secret or credential file '{filename}' is prohibited.") if ext in _BLOCKED_WRITE_EXTENSIONS: raise ValueError(f"Access denied: writing executable/script file type '{ext}' is prohibited.") if any(part in _PROTECTED_WRITE_DIRS for part in parts): raise ValueError(f"Access denied: writing to application source directory '{parts[0]}' is prohibited.") return p class SpeechToTextTool(Tool): """App-local transcriber tool that NEVER imports torch at construction time. smolagents' stock SpeechToTextTool eagerly imports `transformers.models.whisper` in its `__new__` — that transitively pulls in accelerate, which then fails with "No package metadata was found for torch" on machines where torch is not installed. The Store/MSIX build deliberately ships WITHOUT torch (CPU/GPU PyTorch is installed on-demand via Settings), so constructing the stock tool crashed EVERY agentic General/Deep-Research run on that build. A missing torch must degrade, never crash agent construction. Two further fixes over the stock tool, both preserved here: 1. The input schema uses a JSON-Schema-valid `string` type — the stock tool declares `{"audio": {"type": "audio"}}`, and `"audio"` is NOT a valid JSON-Schema type for OpenAI-compatible function calling, so strict HF Inference API providers (DeepInfra, Novita, …) reject the ENTIRE request. 2. Transcription runs through the app's OWN configured STT pipeline (backend.models.transcribe_audio — whisper.cpp server / in-process whisper-cpp / HF Inference API / local HF). That is torch-free on the server and remote providers, already respects the user's Settings STT configuration, and degrades to a clear error message when nothing is configured. """ name = "transcriber" description = ( "This is a tool that transcribes an audio file into text. " "It returns the transcribed text." ) inputs = { "audio": { "type": "string", "description": "Path or URL of the audio file to transcribe.", } } output_type = "string" @staticmethod def _resolve_audio_path(audio) -> Optional[str]: """Resolve the tool input to a local audio file: an existing local path (surrounding quotes stripped) or an http(s) URL downloaded to a temp file. Returns None when the input cannot become a readable file — the caller turns that into a clear error, never a crash.""" if not audio: return None raw = str(audio).strip().strip('"').strip("'") if not raw: return None if raw.lower().startswith(("http://", "https://")): try: import tempfile import urllib.request from urllib.parse import urlparse suffix = Path(urlparse(raw).path).suffix or ".wav" tmp = tempfile.NamedTemporaryFile(suffix=suffix, delete=False) tmp.close() urllib.request.urlretrieve(raw, tmp.name) return tmp.name except Exception: return None p = Path(raw).expanduser() return str(p) if p.exists() else None def forward(self, audio: str) -> str: path = self._resolve_audio_path(audio) if path is None: return ( "[transcriber ERROR] Could not read the audio input — pass a " "local audio file path or an http(s) URL to an audio file." ) from backend import models try: text = models.transcribe_audio(path, language="auto") except Exception as exc: # pragma: no cover — defensive return f"[transcriber ERROR] {exc}" text = (text or "").strip() if text.startswith("❌"): # transcribe_audio embeds a full traceback in the failure yield; # surface only the actionable first line (e.g. "No whisper-server # executable is configured…"). first = text.splitlines()[0] if text.splitlines() else text return f"[transcriber ERROR] {first[:200]}" return text if text else "(No speech detected)" class ReadFileTool(Tool): """Reads the text content of a file on disk within the workspace.""" name = "read_file" description = ( "Read the text content of a file on disk. " "Pass the file path relative to the workspace root " "(e.g. '.agents/skills/my_skill/SKILL.md') or an absolute path " "that sits inside the workspace root. " "Returns the full file content as a string. " "Returns an error string if the file does not exist, is binary, " "or exceeds 1 MB. Do NOT use this for audio/image/binary files." ) inputs = { "path": { "type": "string", "description": "Relative or absolute path to the file to read.", } } input_aliases = { "path": ("file_path", "filepath", "file", "filename", "doc", "src"), } output_type = "string" def forward(self, path: str) -> str: try: resolved = _safe_resolve(path, for_write=False) except ValueError as e: return f"[read_file ERROR] {e}" if not resolved.exists(): return f"[read_file ERROR] File not found: '{resolved}'" if not resolved.is_file(): return f"[read_file ERROR] '{resolved}' is not a regular file." size = resolved.stat().st_size if size > _MAX_READ_BYTES: return ( f"[read_file ERROR] File is {size:,} bytes — exceeds the " f"{_MAX_READ_BYTES:,}-byte read limit. Summarize or split it." ) try: return resolved.read_text(encoding="utf-8", errors="replace") except Exception as exc: return f"[read_file ERROR] Could not read '{resolved}': {exc}" class WriteFileTool(Tool): """Writes (or overwrites) a file on disk within the workspace.""" name = "write_file" description = ( "Write text content to a file on disk within the workspace root. " "Creates the file (and any missing parent directories) if it does " "not exist; OVERWRITES it if it already exists. " "Pass the file path relative to the workspace root " "(e.g. '.agents/skills/my_skill/SKILL.md') and the full text " "content to write. Returns a confirmation message with the " "absolute path of the written file, or an error string on failure." ) inputs = { "path": { "type": "string", "description": "Relative or absolute path of the file to write.", }, "content": { "type": "string", "description": "The full text content to write to the file.", }, } input_aliases = { "path": ("file_path", "filepath", "file", "filename", "target"), "content": ("text", "data", "body"), } output_type = "string" def forward(self, path: str, content: str) -> str: try: resolved = _safe_resolve(path, for_write=True) except ValueError as e: return f"[write_file ERROR] {e}" try: resolved.parent.mkdir(parents=True, exist_ok=True) resolved.write_text(content, encoding="utf-8") return f"[write_file OK] Written {len(content):,} chars to '{resolved}'" except Exception as exc: return f"[write_file ERROR] Could not write '{resolved}': {exc}" class DraftCodexSkillTool(Tool): """Drafts a Codex-style SKILL.md from a concise user idea.""" name = "draft_codex_skill" description = ( "Draft a Codex SKILL.md from a user request. Use this when the user " "asks to create, update, or design a reusable Codex skill. This tool " "does not write files; use write_file afterward only if the user wants " "the skill saved." ) inputs = { "idea": { "type": "string", "description": "The user's skill idea or requested workflow.", }, "skill_name": { "type": "string", "description": "Optional short kebab-case skill name.", "default": "", "nullable": True, }, } output_type = "string" @staticmethod def _slug(text: str) -> str: slug = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-") return slug[:48].strip("-") or "custom-skill" def forward(self, idea: str, skill_name: str = "") -> str: idea = (idea or "").strip() if not idea: return "[draft_codex_skill ERROR] Provide a skill idea." name = self._slug(skill_name or idea) description = ( f"Use when the user wants help with {idea}. " "Follow the workflow and constraints in this skill." ) body = ( "---\n" f"name: {name}\n" f"description: {description}\n" "---\n\n" f"# {name.replace('-', ' ').title()}\n\n" "## Workflow\n\n" "1. Identify the user's exact goal and scope.\n" "2. Gather only the context needed for the task.\n" "3. Choose the narrowest reliable action path.\n" "4. Produce the requested artifact or answer.\n" "5. Validate the result before finishing.\n\n" "## Rules\n\n" "- Keep the workflow focused and repeatable.\n" "- Prefer existing project conventions and tools.\n" "- Ask for clarification only when a safe assumption is not possible.\n" "- Do not add unrelated files or broad background prose.\n\n" "## Output\n\n" "- State what scope was used.\n" "- Provide the finished result or exact next action.\n" "- Mention any validation performed or remaining limitation.\n" ) return ( f"Suggested path: .agents/skills/{name}/SKILL.md\n\n" "```markdown\n" f"{body}" "```" ) # Module-level refs to the CURRENT agent's tracked-tool instances, so # chat.py can read/reset them without needing to reach into the agent's # internal tool registry — mirrors rag_agent.py's `_rag_tool` pattern. _search_tool = None _webpage_tool = None _read_file_tool: "Optional[ReadFileTool]" = None _write_file_tool: "Optional[WriteFileTool]" = None _draft_skill_tool: "Optional[DraftCodexSkillTool]" = None # Base instructions — language-directive prepended dynamically by # build_agent_instructions() at agent-build time, so even models that # ignore a per-task hint see the language rule at the system-prompt level. GENERAL_AGENT_INSTRUCTIONS = ( "You are a helpful, friendly assistant.\n\n" "CRITICAL OUTPUT RULE: Output ONLY the direct final response to the user. " "NEVER include your internal monologue, planning notes, or prompt analysis in your answer.\n\n" "Available tools: `web_search`, `visit_webpage`, `transcriber`, " "`read_file`, `write_file`, `draft_codex_skill`. There is NO other tool " "\u2014 in particular no `conversation_history`, `memory`, or " "`get_previous_messages` function. Never call, import, or reference " "anything not listed; it will fail and waste a step.\n\n" "YOUR OWN CONVERSATION HISTORY IS ALREADY VISIBLE TO YOU: every earlier " "user message and your own earlier replies are already included in what " "you can see \u2014 you do not need a tool to retrieve them. If asked what " "was said earlier, look back at the earlier turns and answer from them " "directly \u2014 do NOT guess.\n\n" "Use web_search/visit_webpage only when a question needs current " "information or specific facts you're unsure of. For simple, timeless, " "conversational questions answerable from your own knowledge, just " "answer directly.\n\n" "If the user asks to create or revise a Codex skill, save the SKILL.md " "with `write_file` to '.agents/skills//' \u2014 write it to " "disk so it is immediately usable, don't just output the content in chat.\n\n" "DON'T REPEAT SEARCHES: never run the exact same web_search query twice " "in one turn. Once you have enough information, stop searching and write " "your final answer.\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." ) # Khmer-only no-reasoning instruction — GLM-4.7-Flash and similar local # GGUF models sometimes output their entire chain-of-thought in Khmer # (instead of wrapping it in tags or calling final_answer directly), # producing meta-reasoning like "សំណួររបស់អ្នកប្រើគឺ..." ("The user's # question is...") as the final answer. Placing this rule in Khmer at the # TOP of the system prompt — before the English instructions — ensures # even small models that anchor on Khmer system text see the rule. _KHMER_NO_REASONING_INSTRUCTION = ( "⚠️ ការណែនាំសំខាន់៖ កុំសរសេរការវិភាគ ការគិតខាងក្នុង ឬការរៀបចំផែនការ " "នៅក្នុងចម្លើយរបស់អ្នកឡើយ។ កុំសរសេរអ្វីដូចជា \"សំណួររបស់អ្នកប្រើគឺ...\" " "ឬ \"ខ្ញុំមិនត្រូវការប្រើ tool...\" ឬ \"ដូច្នេះខ្ញុំគិតថា...\" ក្នុងចម្លើយ។ " "ផ្តល់តែចម្លើយចុងក្រោយដោយផ្ទាល់ប៉ុណ្ណោះ។\n\n" ) def build_agent_instructions(lang_key: str = "kh") -> str: """Return GENERAL_AGENT_INSTRUCTIONS with the output-language directive prepended as the very first line of the system prompt. Injecting the rule here (system-prompt level, applied once at agent-build time) is more reliable than the per-task-message approach alone: small/weak GGUF models that ignore a language hint buried inside the user-turn task text still tend to comply when they see it as a top-level SYSTEM instruction. Both layers are kept (system + per-task) for maximum coverage. """ lang_directive = i18n._output_lang_instruction(lang_key) # For Khmer UI: prepend the Khmer no-reasoning instruction BEFORE the # English instructions so the model sees the rule in its UI language first. no_reasoning = _KHMER_NO_REASONING_INSTRUCTION if lang_key == "kh" else "" return lang_directive + no_reasoning + GENERAL_AGENT_INSTRUCTIONS def build_task_with_citation_reminder(user_message: str, lang_key: str = "kh") -> str: """Wrap the user's message with an explicit, PER-TASK reminder of the citation requirement — a second layer on top of GENERAL_AGENT_INSTRUCTIONS, mirroring rag_agent.build_strict_task()'s "belt and braces" reasoning exactly. Why this is needed: GENERAL_AGENT_INSTRUCTIONS (including its citation requirement) is only ever attached to the agent if this installed smolagents version's chosen agent class (CodeAgent or ToolCallingAgent) happens to expose an `instructions=` parameter — see the `if "instructions" in params: kwargs["instructions"] = ...` guard in agents/agent_factory.py's build_smol_agent(). On a smolagents version where that parameter doesn't exist, that assignment is silently skipped and the model never sees the citation requirement AT ALL — it has no way to know it's supposed to write a '### References' section, so chat.py's resolve_actually_used_sources() always finds nothing to parse, even after a turn that genuinely searched the web. Repeating the requirement here, in the per-call task text (which always reaches the model regardless of smolagents version), closes that gap — same reasoning rag_agent.py already applies to its own strict-grounding instructions. """ # The task text IS the user turn the model sees (smolagents places it # in the user message), so the question must be the LAST line — a small # GGUF model anchors on whatever comes right before its own turn, and # the "answers the system prompt" failure class fires when the # question is buried at the start behind instruction blocks (see # chat_general_direct's matching anchor for the direct path). return ( i18n._output_lang_instruction(lang_key) + i18n._task_preamble(lang_key) + i18n._task_citation_reminder(lang_key) + i18n._task_conciseness_directive(lang_key) + "\n\n---\n" + i18n._task_question_label(lang_key) + f"{user_message}" ) GENERAL_AGENT_DEFAULT_MAX_STEPS = 8 def _build_agent(llm, model_id: str = "", max_steps: Optional[int] = None, execution_timeout: Optional[int] = None, use_tool_calling: bool = True, lang_key: str = "kh"): global _search_tool, _webpage_tool, _read_file_tool, _write_file_tool, _draft_skill_tool _search_tool = TrackedDuckDuckGoSearchTool() _webpage_tool = TrackedVisitWebpageTool() _read_file_tool = ReadFileTool() _write_file_tool = WriteFileTool() _draft_skill_tool = DraftCodexSkillTool() if max_steps is None: max_steps = mr.get_max_steps_for_model(model_id, GENERAL_AGENT_DEFAULT_MAX_STEPS) agent = build_smol_agent( llm, tools=[_search_tool, _webpage_tool, SpeechToTextTool(), _read_file_tool, _write_file_tool, _draft_skill_tool], max_steps=max_steps, use_tool_calling=use_tool_calling, instructions=build_agent_instructions(lang_key), execution_timeout=execution_timeout, ) print(f"[GeneralAgent] Building {type(agent).__name__} on '{model_id or '(shared)'}' …") return agent def reset_tool_usage() -> None: """Call right before agent.run() so this run's tracked queries/URLs start from zero — mirrors rag_agent.reset_retriever_stats().""" if _search_tool is not None: _search_tool.queries_run = [] _search_tool.result_links = [] if _webpage_tool is not None: _webpage_tool.urls_visited = [] # ReadFileTool / WriteFileTool are stateless per-call; nothing to reset. def get_tool_usage() -> tuple: """Call right after agent.run() returns. Returns (queries_run, urls_visited, result_links) — the ACTUAL search queries run, pages explicitly visited via visit_webpage, and (title, url) pairs actually surfaced by web_search's own results this turn — tracked directly by the tools themselves rather than trusting the model's own in-text citations (see the TrackedDuckDuckGoSearchTool / TrackedVisitWebpageTool docstring above for why). `result_links` is what should be used to build a real, clickable references list — the raw query string alone is not a citable source.""" queries = list(_search_tool.queries_run) if _search_tool is not None else [] urls = list(_webpage_tool.urls_visited) if _webpage_tool is not None else [] links = list(_search_tool.result_links) if _search_tool is not None else [] return queries, urls, links def get_general_agent(model_id: Optional[str] = None, max_steps: Optional[int] = None, execution_timeout: Optional[int] = None, use_tool_calling: bool = True, provider: Optional[str] = None, lang_key: str = "kh", n_ctx: Optional[int] = None): """Lazily build (or rebuild, if the model/settings changed) the agentic General Chat CodeAgent or ToolCallingAgent. `lang_key` is included in the cache key so that switching UI language forces a rebuild with a fresh system-prompt language directive — without this the agent built for Khmer would keep its Khmer system prompt even after the user switches to English, and vice-versa. `n_ctx` (optional): this tab's context window, threaded straight through to models.get_llm() so a per-tab n_ctx change rebuilds the agent with the freshly (re)loaded model. Included in the cache key for that reason. """ global _general_agent, _general_agent_model_id global _general_agent_max_steps, _general_agent_execution_timeout global _general_agent_lang_key, _general_agent_n_ctx target = model_id or models._llm_model_id if (_general_agent is not None and target == _general_agent_model_id and max_steps == _general_agent_max_steps and execution_timeout == _general_agent_execution_timeout and lang_key == _general_agent_lang_key and n_ctx == _general_agent_n_ctx): return _general_agent with _general_agent_lock: if (_general_agent is not None and target == _general_agent_model_id and max_steps == _general_agent_max_steps and execution_timeout == _general_agent_execution_timeout and lang_key == _general_agent_lang_key and n_ctx == _general_agent_n_ctx): return _general_agent llm = models.get_llm(target, provider=provider, n_ctx=n_ctx) _general_agent = _build_agent(llm, target, max_steps, execution_timeout, use_tool_calling=use_tool_calling, lang_key=lang_key) _general_agent_model_id = target _general_agent_max_steps = max_steps _general_agent_execution_timeout = execution_timeout _general_agent_lang_key = lang_key _general_agent_n_ctx = n_ctx return _general_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 General Chat model changes or the LLM is force-reloaded/ unloaded elsewhere, so this agent doesn't keep holding a stale model reference — mirrors rag_agent.reset_agent() / data_analysis.reset_agent(). """ global _general_agent, _general_agent_model_id, _search_tool, _webpage_tool global _general_agent_max_steps, _general_agent_execution_timeout global _general_agent_lang_key, _general_agent_n_ctx, _read_file_tool, _write_file_tool _general_agent = None _general_agent_model_id = None _general_agent_max_steps = None _general_agent_execution_timeout = None _general_agent_lang_key = None _general_agent_n_ctx = None _search_tool = None _webpage_tool = None _read_file_tool = None _write_file_tool = None