Download agent.py from JuloEco/Opsiom: direct link, hf CLI and curl.
- Browser
- Download file 35.9 kB
-
https://huggingface.co/spaces/JuloEco/Opsiom/resolve/main/agent.py
- Command line
-
hf download hf://spaces/JuloEco/Opsiom/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/JuloEco/Opsiom/resolve/main/agent.py
35.9 kB
| # ============================================================================ | |
| # Opsiom Kaïro — outils et détection des balises (modes « Raisonnement » et « Agent ») | |
| # | |
| # Ce module ne dépend NI de PyTorch NI de Flask : il contient uniquement la | |
| # logique qu'on veut pouvoir tester seule. | |
| # | |
| # 1. Les balises (texte ordinaire : le tokenizer 32k n'a que <pad>, <unk>, | |
| # <bos>, <eos>) — identiques à celles du fine-tuning | |
| # (opsiom_500m_train_chat.py, phases 2 et 3) : | |
| # <reasoning> … </reasoning> raisonnement (masqué dans l'UI) | |
| # <|tool_call|>{json}<|/tool_call|> appel d'outil généré par le modèle | |
| # \n<|tool_result|>{json}<|/tool_result|>\n résultat injecté PAR LE PROGRAMME | |
| # | |
| # 2. TagParser : découpe le flux généré en réponse visible / raisonnement / | |
| # appel d'outil, et refuse tout ce qu'un modèle ne doit pas écrire lui-même | |
| # (un faux <|tool_result|>, un faux tour <|Utilisateur|>…). Un modèle qui | |
| # « répond » sans avoir exécuté l'outil est donc stoppé net : c'est ce qui | |
| # empêche les outils d'être appelés — ou simulés — « en l'air ». | |
| # | |
| # 3. Les trois outils, réellement exécutés : | |
| # calculator calculatrice AST (aucun eval/exec) | |
| # rag_search recherche dans les documents du COMPTE (téléversés dans | |
| # l'interface) + un dossier partagé optionnel | |
| # web_search SearXNG (OPSIOM_SEARX_URL) ; à défaut, Wikipédia FR | |
| # | |
| # Les formats d'appel/résultat (clés, ordre, sérialisation compacte) sont | |
| # EXACTEMENT ceux de l'entraînement : ne pas les « améliorer » sans ré-entraîner. | |
| # | |
| # Variables d'environnement (toutes optionnelles) : | |
| # OPSIOM_SEARX_URL instance SearXNG (format=json activé) pour web_search | |
| # OPSIOM_WEB_SEARCH "0" : désactive web_search (renvoie « outil indisponible ») | |
| # OPSIOM_USER_AGENT User-Agent des requêtes web (Wikipédia en exige un) | |
| # OPSIOM_RAG_DIR dossier des documents par compte | |
| # (défaut : /data/opsiom_rag si /data existe, sinon ./.opsiom_rag) | |
| # OPSIOM_RAG_SHARED_DIR dossier de .txt/.md visible par tous les comptes | |
| # OPSIOM_RAG_MAX_DOCS / OPSIOM_RAG_MAX_DOC_CHARS / OPSIOM_RAG_MAX_TOTAL_CHARS | |
| # limites par compte (défaut 20 / 300 000 / 2 000 000) | |
| # ============================================================================ | |
| from __future__ import annotations | |
| import ast | |
| import json | |
| import logging | |
| import math | |
| import operator | |
| import os | |
| import re | |
| import threading | |
| import time | |
| import unicodedata | |
| import urllib.parse | |
| import urllib.request | |
| import uuid | |
| from collections import Counter | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any, Optional | |
| logger = logging.getLogger("opsiom_frontend.agent") | |
| # ============================================================================ | |
| # Balises | |
| # ============================================================================ | |
| USER_TAG = "<|Utilisateur|>" | |
| ASSISTANT_TAG = "<|Assistant|>" | |
| REASONING_OPEN = "<reasoning>" | |
| REASONING_CLOSE = "</reasoning>" | |
| TOOL_CALL_OPEN, TOOL_CALL_CLOSE = "<|tool_call|>", "<|/tool_call|>" | |
| TOOL_RES_OPEN, TOOL_RES_CLOSE = "<|tool_result|>", "<|/tool_result|>" | |
| EOS_TEXT = "<eos>" | |
| CONTROL_TAGS = (USER_TAG, ASSISTANT_TAG, REASONING_OPEN, REASONING_CLOSE, TOOL_CALL_OPEN, TOOL_CALL_CLOSE, | |
| TOOL_RES_OPEN, TOOL_RES_CLOSE, EOS_TEXT, "<bos>", "<pad>") | |
| TOOL_NAMES = ("calculator", "rag_search", "web_search") | |
| TOOL_LABELS = {"calculator": "Calculatrice", "rag_search": "Documents (RAG)", "web_search": "Recherche web"} | |
| MAX_TOOL_CALLS = 4 # appels d'outils par question (comme à l'entraînement) | |
| MAX_CALL_CHARS = 700 # un appel plus long n'est pas un appel : le modèle déraille | |
| MAX_EXPR_CHARS = 200 | |
| MAX_RESULT_CHARS = 1800 # un résultat injecté ne dépasse jamais cette taille | |
| def tjson(obj: Any) -> str: | |
| """Sérialisation UNIQUE des appels et résultats (entraînement ET exécution : identiques).""" | |
| return json.dumps(obj, ensure_ascii=False, separators=(",", ":")) | |
| def strip_accents(text: str) -> str: | |
| return "".join(c for c in unicodedata.normalize("NFKD", text) if not unicodedata.combining(c)) | |
| def clean_untrusted(value: Any) -> str: | |
| """Texte venu d'un document ou d'une page web : les balises de contrôle sont neutralisées. | |
| Sans ça, une page pourrait fabriquer un faux <|tool_call|> ou un <eos>, qui serait un VRAI | |
| token une fois passé au tokenizer (injection de prompt).""" | |
| text = str(value) | |
| for tag in CONTROL_TAGS: | |
| text = text.replace(tag, "[balise retirée]") | |
| return text | |
| def fr_num(x: Any) -> str: | |
| """Nombre à la française : espaces pour les milliers, virgule décimale (4 décimales max).""" | |
| if isinstance(x, float) and x.is_integer(): | |
| x = int(x) | |
| if isinstance(x, int): | |
| return f"{x:,}".replace(",", " ") | |
| return f"{x:,.4f}".rstrip("0").rstrip(".").replace(",", " ").replace(".", ",") | |
| # ============================================================================ | |
| # Calculatrice sécurisée (AST : aucune exécution de code Python arbitraire) | |
| # — copie fidèle de celle de l'entraînement, pour que les résultats soient identiques. | |
| # ============================================================================ | |
| _BIN = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, | |
| ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod, ast.Pow: operator.pow} | |
| _FUNCS = {"sqrt": math.sqrt, "abs": abs, "round": round, "min": min, "max": max} | |
| class CalcError(Exception): | |
| pass | |
| def _calc_node(n: ast.AST, depth: int = 0): | |
| if depth > 40: | |
| raise CalcError("expression invalide") | |
| if isinstance(n, ast.Expression): | |
| return _calc_node(n.body, depth + 1) | |
| if isinstance(n, ast.Constant): | |
| if isinstance(n.value, bool) or not isinstance(n.value, (int, float)): | |
| raise CalcError("expression invalide") | |
| return n.value | |
| if isinstance(n, ast.UnaryOp) and isinstance(n.op, (ast.UAdd, ast.USub)): | |
| v = _calc_node(n.operand, depth + 1) | |
| return v if isinstance(n.op, ast.UAdd) else -v | |
| if isinstance(n, ast.BinOp) and type(n.op) in _BIN: | |
| a, b = _calc_node(n.left, depth + 1), _calc_node(n.right, depth + 1) | |
| if isinstance(n.op, ast.Pow): | |
| if abs(b) > 1000 or (abs(a) > 1e9 and abs(b) > 10): | |
| raise CalcError("nombre trop grand") | |
| if isinstance(a, int) and isinstance(b, int) and b > 0 and abs(a) > 1 and abs(a).bit_length() * b > 4096: | |
| raise CalcError("nombre trop grand") | |
| try: | |
| v = _BIN[type(n.op)](a, b) | |
| except ZeroDivisionError: | |
| raise CalcError("division par zéro") | |
| except OverflowError: | |
| raise CalcError("nombre trop grand") | |
| if isinstance(v, complex): | |
| raise CalcError("résultat non réel") | |
| return v | |
| if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id in _FUNCS \ | |
| and not n.keywords and 1 <= len(n.args) <= 4: | |
| args = [_calc_node(x, depth + 1) for x in n.args] | |
| if n.func.id == "sqrt" and (len(args) != 1 or args[0] < 0): | |
| raise CalcError("racine d'un nombre négatif") | |
| try: | |
| return _FUNCS[n.func.id](*args) | |
| except (TypeError, ValueError, OverflowError): | |
| raise CalcError("expression invalide") | |
| raise CalcError("expression invalide") | |
| def safe_eval(expr: Any): | |
| if not isinstance(expr, str) or not expr.strip() or len(expr) > MAX_EXPR_CHARS: | |
| raise CalcError("expression invalide") | |
| expr = expr.replace("×", "*").replace("÷", "/").replace("^", "**") # seules normalisations tolérées | |
| try: | |
| tree = ast.parse(expr.strip(), mode="eval") | |
| except (SyntaxError, ValueError, RecursionError, MemoryError): | |
| raise CalcError("expression invalide") | |
| v = _calc_node(tree) | |
| if isinstance(v, float): | |
| if math.isnan(v) or math.isinf(v): | |
| raise CalcError("résultat invalide") | |
| v = round(v, 10) | |
| if v.is_integer() and abs(v) < 1e15: | |
| v = int(v) | |
| elif isinstance(v, int) and v.bit_length() > 4096: | |
| raise CalcError("nombre trop grand") | |
| return v | |
| def calc_tool(expr: Any) -> dict: | |
| """Résultat d'outil de la calculatrice : {"result": n} ou {"error": "..."}.""" | |
| try: | |
| v = safe_eval(expr) | |
| except CalcError as exc: | |
| return {"error": str(exc)} | |
| return {"result": v if isinstance(v, int) else round(v, 6)} | |
| # ============================================================================ | |
| # RAG : documents par compte | |
| # ============================================================================ | |
| def _env_int(name: str, default: int) -> int: | |
| try: | |
| return max(1, int(os.environ.get(name, ""))) | |
| except ValueError: | |
| return default | |
| RAG_MAX_DOCS = _env_int("OPSIOM_RAG_MAX_DOCS", 20) | |
| RAG_MAX_DOC_CHARS = _env_int("OPSIOM_RAG_MAX_DOC_CHARS", 300_000) | |
| RAG_MAX_TOTAL_CHARS = _env_int("OPSIOM_RAG_MAX_TOTAL_CHARS", 2_000_000) | |
| RAG_CHUNK_CHARS = 500 # taille des extraits (comme à l'entraînement) | |
| RAG_SNIPPET_CHARS = 400 # taille d'un extrait renvoyé au modèle | |
| _DOC_ID = re.compile(r"^[0-9a-f]{12}$") | |
| class DocError(Exception): | |
| """Erreur lisible, affichée telle quelle à la personne.""" | |
| def _hard_wrap(paragraph: str, limit: int) -> list[str]: | |
| """Coupe un très long paragraphe en morceaux ≤ limit, de préférence sur une espace.""" | |
| pieces: list[str] = [] | |
| rest = paragraph | |
| while len(rest) > limit: | |
| cut = rest.rfind(" ", 0, limit) | |
| cut = cut if cut > limit // 2 else limit | |
| pieces.append(rest[:cut].strip()) | |
| rest = rest[cut:].strip() | |
| if rest: | |
| pieces.append(rest) | |
| return pieces | |
| def split_chunks(text: str) -> list[str]: | |
| """Paragraphes regroupés en extraits d'au plus ~500 caractères.""" | |
| chunks: list[str] = [] | |
| cur = "" | |
| for para in re.split(r"\n\s*\n", text): | |
| para = " ".join(para.split()) | |
| if not para: | |
| continue | |
| for piece in (_hard_wrap(para, RAG_CHUNK_CHARS) if len(para) > RAG_CHUNK_CHARS else [para]): | |
| if cur and len(cur) + len(piece) > RAG_CHUNK_CHARS: | |
| chunks.append(cur) | |
| cur = "" | |
| cur = (cur + " " + piece).strip() | |
| if cur: | |
| chunks.append(cur) | |
| return chunks | |
| class DocStore: | |
| """Documents texte (.txt / .md) rangés par compte, avec recherche TF-IDF par mots-clés. | |
| Un compte ne voit JAMAIS les documents d'un autre : le dossier est dérivé de l'identifiant | |
| numérique du compte, jamais d'une valeur envoyée par le navigateur. Le dossier partagé | |
| (`shared_dir`, optionnel) est, lui, visible par tous les comptes.""" | |
| STOP = set("le la les un une des de du d l et ou à a au aux en dans sur pour par avec que qui quoi est sont ce cet " | |
| "cette ces se sa son ses mon ma mes ton ta tes il elle on nous vous ils elles ne pas plus comme mais " | |
| "donc car".split()) | |
| def __init__(self, root: "str | Path", shared_dir: "str | Path | None" = None): | |
| self.root = Path(root) | |
| self.shared_dir = Path(shared_dir) if shared_dir else None | |
| self._lock = threading.RLock() | |
| self._cache: dict[int, tuple[tuple, list[tuple[str, str]], dict[str, float]]] = {} | |
| # -- chemins ------------------------------------------------------------- | |
| def _udir(self, user_id: Any) -> Path: | |
| try: | |
| uid = int(user_id) | |
| except (TypeError, ValueError): | |
| raise DocError("Compte invalide.") | |
| if uid <= 0: | |
| raise DocError("Compte invalide.") | |
| return self.root / f"u{uid}" | |
| # -- gestion ------------------------------------------------------------- | |
| def _clean_name(name: Any) -> str: | |
| base = Path(str(name or "document")).name | |
| base = re.sub(r"[^\w .()\-]", "_", base).strip() | |
| return base[:80] or "document" | |
| def _clean_text(text: Any) -> str: | |
| if not isinstance(text, str): | |
| raise DocError("Contenu invalide.") | |
| if "\x00" in text: | |
| raise DocError("Fichier binaire ou illisible : seuls les textes (.txt, .md) sont acceptés.") | |
| text = text.replace("\r\n", "\n").replace("\r", "\n").strip() | |
| if not text: | |
| raise DocError("Le document est vide.") | |
| if len(text) > RAG_MAX_DOC_CHARS: | |
| raise DocError(f"Document trop long ({len(text):,} caractères ; maximum {RAG_MAX_DOC_CHARS:,}).".replace(",", " ")) | |
| return text | |
| def _read(self, path: Path) -> Optional[dict]: | |
| try: | |
| data = json.loads(path.read_text(encoding="utf-8")) | |
| except (OSError, ValueError): | |
| return None | |
| return data if isinstance(data, dict) else None | |
| def list(self, user_id: Any) -> list[dict]: | |
| folder = self._udir(user_id) | |
| docs: list[dict] = [] | |
| if folder.is_dir(): | |
| for path in folder.glob("*.json"): | |
| if not _DOC_ID.match(path.stem): | |
| continue | |
| doc = self._read(path) | |
| if doc: | |
| docs.append({"id": path.stem, "name": str(doc.get("name") or "document"), | |
| "chars": len(str(doc.get("text") or "")), "created": doc.get("created") or 0}) | |
| docs.sort(key=lambda d: d["created"]) | |
| return docs | |
| def usage(self, user_id: Any) -> dict: | |
| docs = self.list(user_id) | |
| return {"count": len(docs), "chars": sum(d["chars"] for d in docs), "max_docs": RAG_MAX_DOCS, | |
| "max_doc_chars": RAG_MAX_DOC_CHARS, "max_total_chars": RAG_MAX_TOTAL_CHARS, | |
| "shared": self._shared_count()} | |
| def add(self, user_id: Any, name: Any, text: Any) -> dict: | |
| clean_name, clean_text = self._clean_name(name), self._clean_text(text) | |
| with self._lock: | |
| docs = self.list(user_id) | |
| if len(docs) >= RAG_MAX_DOCS: | |
| raise DocError(f"Limite atteinte : {RAG_MAX_DOCS} documents maximum. Supprime-en un d'abord.") | |
| if sum(d["chars"] for d in docs) + len(clean_text) > RAG_MAX_TOTAL_CHARS: | |
| raise DocError("Espace de documents plein pour ce compte. Supprime-en un d'abord.") | |
| doc_id = uuid.uuid4().hex[:12] | |
| folder = self._udir(user_id) | |
| folder.mkdir(parents=True, exist_ok=True) | |
| created = time.time() | |
| tmp = folder / f"{doc_id}.tmp" | |
| tmp.write_text(json.dumps({"name": clean_name, "text": clean_text, "created": created}, | |
| ensure_ascii=False), encoding="utf-8") | |
| os.replace(tmp, folder / f"{doc_id}.json") | |
| self._cache.pop(int(user_id), None) | |
| return {"id": doc_id, "name": clean_name, "chars": len(clean_text), "created": created} | |
| def delete(self, user_id: Any, doc_id: Any) -> bool: | |
| if not isinstance(doc_id, str) or not _DOC_ID.match(doc_id): | |
| return False | |
| with self._lock: | |
| path = self._udir(user_id) / f"{doc_id}.json" | |
| try: | |
| path.unlink() | |
| except FileNotFoundError: | |
| return False | |
| self._cache.pop(int(user_id), None) | |
| return True | |
| def clear(self, user_id: Any) -> int: | |
| removed = 0 | |
| for doc in self.list(user_id): | |
| removed += self.delete(user_id, doc["id"]) | |
| return removed | |
| # -- recherche ----------------------------------------------------------- | |
| def _shared_files(self) -> list[Path]: | |
| if not self.shared_dir or not self.shared_dir.is_dir(): | |
| return [] | |
| found = [p for p in self.shared_dir.rglob("*") if p.is_file() and p.suffix.lower() in (".txt", ".md")] | |
| return sorted(found)[:500] | |
| def _shared_count(self) -> int: | |
| return len(self._shared_files()) | |
| def has_documents(self, user_id: Any) -> bool: | |
| folder = self._udir(user_id) | |
| return (folder.is_dir() and any(folder.glob("*.json"))) or bool(self._shared_files()) | |
| def _tokens(self, text: str) -> list[str]: | |
| return [w for w in re.findall(r"\w+", strip_accents(text.lower())) if len(w) >= 3 and w not in self.STOP] | |
| def _index(self, user_id: Any): | |
| uid = int(user_id) | |
| folder = self._udir(uid) | |
| user_files = sorted(folder.glob("*.json")) if folder.is_dir() else [] | |
| shared_files = self._shared_files() | |
| signature = [] | |
| for path in user_files + shared_files: | |
| try: | |
| st = path.stat() | |
| except OSError: | |
| continue | |
| signature.append((str(path), st.st_mtime_ns, st.st_size)) | |
| signature_t = tuple(signature) | |
| with self._lock: | |
| cached = self._cache.get(uid) | |
| if cached and cached[0] == signature_t: | |
| return cached[1], cached[2] | |
| sources: list[tuple[str, str]] = [] | |
| for path in user_files: | |
| doc = self._read(path) | |
| if doc and _DOC_ID.match(path.stem): | |
| sources.append((str(doc.get("name") or "document"), str(doc.get("text") or ""))) | |
| for path in shared_files: | |
| try: | |
| sources.append((path.name, path.read_text(encoding="utf-8", errors="ignore")[:5_000_000])) | |
| except OSError: | |
| continue | |
| chunks: list[tuple[str, str]] = [(name, chunk) for name, text in sources for chunk in split_chunks(text)] | |
| df: Counter = Counter() | |
| for _, chunk in chunks: | |
| df.update(set(self._tokens(chunk))) | |
| n = max(1, len(chunks)) | |
| idf = {w: math.log(1 + n / c) for w, c in df.items()} | |
| with self._lock: | |
| self._cache[uid] = (signature_t, chunks, idf) | |
| return chunks, idf | |
| def search(self, user_id: Any, query: str, top_k: int = 5) -> list[dict]: | |
| chunks, idf = self._index(user_id) | |
| query_tokens = set(self._tokens(query)) | |
| scored: list[tuple[float, str, str]] = [] | |
| for source, text in chunks: | |
| counts = Counter(self._tokens(text)) | |
| score = sum(idf.get(w, 0.0) * (1 + math.log(counts[w])) for w in query_tokens if w in counts) | |
| if score > 0: | |
| scored.append((score, source, text)) | |
| scored.sort(key=lambda item: -item[0]) | |
| return [{"text": clean_untrusted(text)[:RAG_SNIPPET_CHARS], "source": clean_untrusted(source)} | |
| for _, source, text in scored[:top_k]] | |
| _DOCSTORE: Optional[DocStore] = None | |
| _DOCSTORE_LOCK = threading.Lock() | |
| def default_rag_root() -> Path: | |
| configured = os.environ.get("OPSIOM_RAG_DIR", "").strip() | |
| if configured: | |
| return Path(configured) | |
| data = Path("/data") | |
| if data.is_dir() and os.access(data, os.W_OK): | |
| return data / "opsiom_rag" | |
| return Path(__file__).resolve().parent / ".opsiom_rag" | |
| def get_docstore() -> DocStore: | |
| """Instance unique, partagée par app.py (téléversements) et inference.py (outil rag_search).""" | |
| global _DOCSTORE | |
| with _DOCSTORE_LOCK: | |
| if _DOCSTORE is None: | |
| _DOCSTORE = DocStore(default_rag_root(), os.environ.get("OPSIOM_RAG_SHARED_DIR", "").strip() or None) | |
| return _DOCSTORE | |
| # ============================================================================ | |
| # Recherche web : SearXNG, sinon Wikipédia FR | |
| # ============================================================================ | |
| WEB_TIMEOUT = 10 | |
| _USER_AGENT = os.environ.get("OPSIOM_USER_AGENT", "OpsiomBot/1.0 (+https://huggingface.co/spaces/JuloEco/Opsiom)") | |
| def _searx_url() -> str: | |
| return os.environ.get("OPSIOM_SEARX_URL", "").strip().rstrip("/") | |
| def web_backend() -> str: | |
| """'searxng' | 'wikipedia' | 'off' — ce que web_search utilisera réellement.""" | |
| if os.environ.get("OPSIOM_WEB_SEARCH", "1").strip() == "0": | |
| return "off" | |
| return "searxng" if _searx_url() else "wikipedia" | |
| def _http_json(url: str, timeout: float = WEB_TIMEOUT, max_bytes: int = 2_000_000) -> Any: | |
| if urllib.parse.urlsplit(url).scheme not in ("http", "https"): | |
| raise ValueError("schéma d'URL refusé") | |
| request = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT, "Accept": "application/json"}) | |
| with urllib.request.urlopen(request, timeout=timeout) as response: | |
| return json.loads(response.read(max_bytes).decode("utf-8", "ignore")) | |
| def _web_searx(query: str) -> list[dict]: | |
| url = f"{_searx_url()}/search?" + urllib.parse.urlencode({"q": query, "format": "json", "language": "fr"}) | |
| data = _http_json(url) | |
| return [{"title": clean_untrusted(x.get("title", ""))[:120], "snippet": clean_untrusted(x.get("content", ""))[:300], | |
| "url": clean_untrusted(x.get("url", ""))[:200]} for x in (data.get("results") or [])[:5]] | |
| def _web_wikipedia(query: str) -> list[dict]: | |
| params = {"action": "query", "generator": "search", "gsrsearch": query, "gsrlimit": "4", "gsrnamespace": "0", | |
| "prop": "extracts|info", "exintro": "1", "explaintext": "1", "exchars": "320", "exlimit": "4", | |
| "inprop": "url", "format": "json", "formatversion": "2", "utf8": "1"} | |
| data = _http_json("https://fr.wikipedia.org/w/api.php?" + urllib.parse.urlencode(params)) | |
| pages = (data.get("query") or {}).get("pages") or [] | |
| pages = sorted((p for p in pages if isinstance(p, dict)), key=lambda p: p.get("index", 99)) | |
| results = [] | |
| for page in pages[:4]: | |
| snippet = " ".join(str(page.get("extract") or "").split()) | |
| if not snippet: | |
| continue | |
| results.append({"title": clean_untrusted(page.get("title", ""))[:120], "snippet": clean_untrusted(snippet)[:300], | |
| "url": clean_untrusted(page.get("fullurl", ""))[:200]}) | |
| return results | |
| def web_search_tool(args: dict) -> dict: | |
| query = args.get("query") | |
| if not isinstance(query, str) or not query.strip() or len(query) > MAX_EXPR_CHARS: | |
| return {"error": "arguments invalides"} | |
| backend = web_backend() | |
| if backend == "off": | |
| return {"error": "outil indisponible"} | |
| attempts = ([_web_searx] if backend == "searxng" else []) + [_web_wikipedia] | |
| timed_out = False | |
| for attempt in attempts: | |
| try: | |
| return {"results": attempt(query.strip())} | |
| except TimeoutError: | |
| timed_out = True | |
| except Exception as exc: # noqa: BLE001 — une panne réseau ne doit jamais casser la génération | |
| logger.warning(f"web_search ({attempt.__name__}) : {type(exc).__name__}: {exc}") | |
| return {"error": "délai dépassé" if timed_out else "outil indisponible"} | |
| # ============================================================================ | |
| # Exécution des appels (ne lève JAMAIS : toute panne devient {"error": ...}) | |
| # ============================================================================ | |
| class ToolRunner: | |
| """Exécute les appels d'outils d'UN compte, parmi les outils qu'il a laissés activés.""" | |
| def __init__(self, store: DocStore, user_id: Any, enabled: "frozenset[str] | set[str]"): | |
| self.store = store | |
| self.user_id = user_id | |
| self.enabled = frozenset(enabled) & frozenset(TOOL_NAMES) | |
| def _rag(self, args: dict) -> dict: | |
| query, top_k = args.get("query"), args.get("top_k", 5) | |
| if not isinstance(query, str) or not query.strip() or len(query) > MAX_EXPR_CHARS: | |
| return {"error": "arguments invalides"} | |
| top_k = top_k if isinstance(top_k, int) and not isinstance(top_k, bool) and 1 <= top_k <= 10 else 5 | |
| if not self.store.has_documents(self.user_id): | |
| return {"error": "outil indisponible"} | |
| return {"results": self.store.search(self.user_id, query, top_k)} | |
| def _fit(result: dict, limit: int = MAX_RESULT_CHARS) -> dict: | |
| """Un résultat trop gros ferait dépasser le contexte (1024 tokens) : on retire les derniers éléments.""" | |
| if isinstance(result.get("results"), list): | |
| while len(tjson(result)) > limit and result["results"]: | |
| result["results"].pop() | |
| elif len(tjson(result)) > limit: | |
| return {"error": "résultat trop long"} | |
| return result | |
| def run(self, name: Any, args: Any) -> dict: | |
| try: | |
| if name not in TOOL_NAMES: | |
| return {"error": "outil inconnu"} | |
| if name not in self.enabled: | |
| return {"error": "outil indisponible"} | |
| if not isinstance(args, dict): | |
| return {"error": "arguments invalides"} | |
| if name == "calculator": | |
| return calc_tool(args.get("expression")) | |
| if name == "rag_search": | |
| return self._fit(self._rag(args)) | |
| return self._fit(web_search_tool(args)) | |
| except Exception: # noqa: BLE001 | |
| logger.exception("Outil %s : erreur interne", name) | |
| return {"error": "erreur interne"} | |
| def parse_tool_call(raw: str) -> Optional[tuple[str, dict]]: | |
| """Corps JSON d'un appel -> (nom, arguments), ou None si ce n'est pas un appel valide.""" | |
| try: | |
| obj = json.loads(raw.strip()) | |
| except (ValueError, TypeError, AttributeError): | |
| return None | |
| if isinstance(obj, dict) and isinstance(obj.get("name"), str) and isinstance(obj.get("arguments"), dict): | |
| return obj["name"], obj["arguments"] | |
| return None | |
| class ToolExchange: | |
| index: int | |
| name: Optional[str] | |
| arguments: Optional[dict] | |
| valid: bool | |
| result: dict | |
| ok: bool | |
| call_summary: str | |
| result_summary: str | |
| def as_event(self) -> dict: | |
| """Version envoyée au navigateur (jamais le contenu complet d'un document : résumé seulement).""" | |
| return {"index": self.index, "name": self.name, "label": TOOL_LABELS.get(self.name or "", "Appel invalide"), | |
| "valid": self.valid, "ok": self.ok, "call": self.call_summary, "result": self.result_summary} | |
| def summarize_call(name: Optional[str], args: Optional[dict]) -> str: | |
| if not name or not isinstance(args, dict): | |
| return "" | |
| value = args.get("expression") if name == "calculator" else args.get("query") | |
| return str(value if value is not None else "")[:80] | |
| def summarize_result(name: Optional[str], result: dict) -> tuple[bool, str]: | |
| if "error" in result: | |
| return False, str(result["error"])[:80] | |
| if name == "calculator": | |
| return True, "= " + fr_num(result.get("result")) | |
| count = len(result.get("results") or []) | |
| noun = "extrait" if name == "rag_search" else "résultat" | |
| return True, f"{count} {noun}{'s' if count > 1 else ''}" | |
| def execute_call(runner: ToolRunner, raw: str, index: int) -> ToolExchange: | |
| """Valide puis exécute un appel brut généré par le modèle. Un appel invalide ou inconnu ne | |
| plante rien : le modèle reçoit {"error": ...} (cas vu à l'entraînement) et répond en conséquence.""" | |
| parsed = parse_tool_call(raw) | |
| if parsed is None: | |
| result: dict = {"error": "appel invalide"} | |
| return ToolExchange(index, None, None, False, result, False, "", "appel invalide") | |
| name, args = parsed | |
| if name not in TOOL_NAMES: | |
| result = {"error": "outil inconnu"} | |
| return ToolExchange(index, name[:40], args, False, result, False, "", "outil inconnu") | |
| result = runner.run(name, args) | |
| ok, summary = summarize_result(name, result) | |
| return ToolExchange(index, name, args, True, result, ok, summarize_call(name, args), summary) | |
| def fit_result_to_budget(result: dict, max_chars: int) -> dict: | |
| """Réduit un résultat pour qu'il tienne dans `max_chars` (budget de contexte restant).""" | |
| return ToolRunner._fit(dict(result, results=list(result["results"])) if isinstance(result.get("results"), list) | |
| else dict(result), max_chars) | |
| def result_injection(result: dict) -> str: | |
| """Texte injecté après un appel — même gabarit que l'entraînement.""" | |
| return "\n" + TOOL_RES_OPEN + tjson(result) + TOOL_RES_CLOSE + "\n" | |
| # ============================================================================ | |
| # Détection des balises dans le flux généré | |
| # ============================================================================ | |
| class TagParser: | |
| """Découpe le texte généré, au fil de l'eau, en évènements : | |
| ("text", s) morceau de réponse visible | |
| ("reasoning_start", None) / ("reasoning", s) / ("reasoning_end", None) | |
| et détecte les arrêts : | |
| pending_call corps brut d'un appel d'outil COMPLET (le programme doit l'exécuter) | |
| halt_reason "fabricated_result" (le modèle a écrit lui-même un résultat d'outil), | |
| "turn_tag" (faux tour Utilisateur/Assistant), "eos", "call_too_long" | |
| Une balise coupée entre deux morceaux (« <|tool_ » puis « call|> ») est retenue jusqu'à | |
| ce qu'on sache si c'en est une ; les balises inconnues restent du texte ordinaire. | |
| `tools_allowed=False` : un appel d'outil généré est avalé sans être exécuté.""" | |
| def __init__(self, *, tools_allowed: bool): | |
| self.tools_allowed = tools_allowed | |
| self.visible = "" | |
| self.reasoning = "" | |
| self.had_reasoning = False | |
| self.reasoning_unclosed = False | |
| self.dropped_calls = 0 | |
| self.halt_reason: Optional[str] = None | |
| self.pending_call: Optional[str] = None | |
| self._buf = "" | |
| self._state = "answer" # answer | reasoning | call | skip | |
| self._call_raw = "" | |
| self._started = False | |
| # -- état ---------------------------------------------------------------- | |
| def in_call(self) -> bool: | |
| return self._state == "call" | |
| def stopped(self) -> bool: | |
| return self.halt_reason is not None or self.pending_call is not None | |
| def next_round(self) -> None: | |
| """Après l'injection d'un résultat d'outil : le modèle reprend en mode réponse.""" | |
| self.pending_call = None | |
| self._buf = "" | |
| self._state = "answer" | |
| self._call_raw = "" | |
| # -- balises --------------------------------------------------------------- | |
| def _first_tag(buf: str) -> tuple[int, Optional[str]]: | |
| best_idx, best_tag = -1, None | |
| for tag in CONTROL_TAGS: | |
| idx = buf.find(tag) | |
| if idx != -1 and (best_tag is None or idx < best_idx): | |
| best_idx, best_tag = idx, tag | |
| return best_idx, best_tag | |
| def _held_len(buf: str) -> int: | |
| """Longueur du plus long suffixe de `buf` qui pourrait être le début d'une balise.""" | |
| longest = max(len(t) for t in CONTROL_TAGS) | |
| for k in range(min(len(buf), longest - 1), 0, -1): | |
| suffix = buf[-k:] | |
| if suffix[0] == "<" and any(tag.startswith(suffix) for tag in CONTROL_TAGS): | |
| return k | |
| return 0 | |
| def _halt(self, reason: str) -> None: | |
| if self.halt_reason is None: | |
| self.halt_reason = reason | |
| def _text(self, text: str, events: list) -> None: | |
| if not text: | |
| return | |
| if self._state == "answer": | |
| if not self._started: | |
| text = text.lstrip() | |
| if not text: | |
| return | |
| self._started = True | |
| self.visible += text | |
| events.append(("text", text)) | |
| elif self._state == "reasoning": | |
| self.reasoning += text | |
| events.append(("reasoning", text)) | |
| elif self._state == "call": | |
| self._call_raw += text | |
| if len(self._call_raw) > MAX_CALL_CHARS: | |
| self._halt("call_too_long") | |
| # état "skip" : appel d'outil non autorisé, ignoré | |
| def _close_reasoning(self, events: list) -> None: | |
| if self._state == "reasoning": | |
| self._state = "answer" | |
| events.append(("reasoning_end", None)) | |
| def _tag(self, tag: str, events: list) -> None: | |
| if tag == REASONING_OPEN: | |
| if self._state == "answer": | |
| self._state = "reasoning" | |
| self.had_reasoning = True | |
| events.append(("reasoning_start", None)) | |
| elif tag == REASONING_CLOSE: | |
| self._close_reasoning(events) | |
| elif tag == TOOL_CALL_OPEN: | |
| self._close_reasoning(events) | |
| if self._state == "answer": | |
| self._call_raw = "" | |
| if self.tools_allowed: | |
| self._state = "call" | |
| else: | |
| self._state = "skip" | |
| self.dropped_calls += 1 | |
| elif tag == TOOL_CALL_CLOSE: | |
| if self._state == "call": | |
| self.pending_call = self._call_raw | |
| self._state = "answer" | |
| elif self._state == "skip": | |
| self._state = "answer" | |
| elif tag in (TOOL_RES_OPEN, TOOL_RES_CLOSE): | |
| self._halt("fabricated_result") # un résultat d'outil n'est JAMAIS écrit par le modèle | |
| elif tag in (USER_TAG, ASSISTANT_TAG): | |
| self._halt("turn_tag") | |
| elif tag == EOS_TEXT: | |
| self._halt("eos") | |
| # <bos> / <pad> : ignorés | |
| # -- flux -------------------------------------------------------------------- | |
| def feed(self, chunk: str) -> list[tuple[str, Any]]: | |
| events: list[tuple[str, Any]] = [] | |
| if self.stopped or not chunk: | |
| return events | |
| self._buf += chunk | |
| while not self.stopped: | |
| idx, tag = self._first_tag(self._buf) | |
| if tag is None: | |
| keep = self._held_len(self._buf) | |
| cut = len(self._buf) - keep | |
| self._text(self._buf[:cut], events) | |
| self._buf = self._buf[cut:] | |
| break | |
| self._text(self._buf[:idx], events) | |
| self._buf = self._buf[idx + len(tag):] | |
| self._tag(tag, events) | |
| return events | |
| def finish(self) -> list[tuple[str, Any]]: | |
| """Fin de génération (eos, limite de tokens, contexte plein) : vide le tampon retenu.""" | |
| events: list[tuple[str, Any]] = [] | |
| if not self.stopped and self._buf: | |
| self._text(self._buf, events) | |
| self._buf = "" | |
| if self._state == "call" and self.pending_call is None and self.halt_reason is None: | |
| # Appel jamais refermé : accepté seulement si le JSON est complet et valide. | |
| if parse_tool_call(self._call_raw) is not None: | |
| self.pending_call = self._call_raw | |
| else: | |
| self.dropped_calls += 1 | |
| self._state = "answer" | |
| if self._state == "reasoning": | |
| self._state = "answer" | |
| self.reasoning_unclosed = True | |
| events.append(("reasoning_end", None)) | |
| return events | |