Opsiom / tools.py
JuloEco's picture
Upload 31 files
967429f verified
Raw History Blame Contribute Delete
19.8 kB
# ============================================================================
# Opsiom — outils de l'agent (« Kaïro Tools ») : calculatrice, recherche web, RAG
#
# Ce module est le pendant SERVEUR de la phase 3 de opsiom_500m_chat_sft.py :
# mêmes balises, même sérialisation JSON, même calculatrice. Il ne dépend pas de
# torch (testable seul : tests/test_tools.py).
#
# Flux (UN SEUL tour assistant continu, voir le script d'entraînement) :
# <|Utilisateur|>\n{question}\n<|Assistant|>\n
# <|tool_call|>{"name":…,"arguments":{…}}<|/tool_call|> <- généré par le modèle
# \n<|tool_result|>{…}<|/tool_result|>\n <- injecté par le serveur
# {réponse finale}<eos>
#
# Trois couches de protection, pour que le modèle n'appelle pas un outil « en l'air » :
# 1. DÉTECTION : parse_tool_call() ne retient qu'un appel bien formé
# {"name": str, "arguments": dict} avec un outil connu.
# 2. UTILITÉ : ToolGate.check() juge si l'appel sert à quelque chose
# (salutation, aucun nombre dans la question, requête sans rapport
# avec la question, appel déjà fait, outil désactivé…).
# Un appel inutile est ANNULÉ (le serveur efface l'appel et
# redemande une réponse directe) — l'utilisateur ne le voit jamais.
# 3. EXÉCUTION : ToolBox.run() ne lève jamais : toute panne devient {"error": …}
# (messages identiques à ceux vus au fine-tuning), les textes venus
# du web / des documents sont neutralisés (clean_untrusted) pour
# qu'une page ne puisse pas fabriquer un faux <|tool_call|> ou <eos>.
# ============================================================================
import ast
import json
import logging
import math
import operator
import os
import re
import unicodedata
import urllib.parse
from collections import Counter
from dataclasses import dataclass, field
logger = logging.getLogger("opsiom_frontend.tools")
# --- Balises (identiques au fine-tuning) -------------------------------------
USER_TAG = "<|Utilisateur|>"
ASSISTANT_TAG = "<|Assistant|>"
EOS_TOKEN = "<eos>"
REASONING_OPEN, REASONING_CLOSE = "<reasoning>", "</reasoning>"
TOOL_CALL_OPEN, TOOL_CALL_CLOSE = "<|tool_call|>", "<|/tool_call|>"
TOOL_RES_OPEN, TOOL_RES_CLOSE = "<|tool_result|>", "<|/tool_result|>"
TOOL_NAMES = ("calculator", "rag_search", "web_search")
MAX_TOOL_CALLS = 4 # appels max par question (section 8 du brief)
MAX_EXPR_CHARS = 200
MAX_QUERY_CHARS = 200
MAX_RESULT_CHARS = 1800 # un résultat injecté ne dépasse jamais cette taille
# Ce que le serveur dit à l'interface sur chaque outil.
TOOL_LABELS = {"web_search": "Recherche web", "calculator": "Calculatrice", "rag_search": "Mes documents"}
_RESERVED = (TOOL_CALL_OPEN, TOOL_CALL_CLOSE, TOOL_RES_OPEN, TOOL_RES_CLOSE, USER_TAG, ASSISTANT_TAG,
EOS_TOKEN, "<bos>", "<pad>", "<|endoftext|>", REASONING_OPEN, REASONING_CLOSE)
def tjson(o) -> str:
"""Sérialisation UNIQUE des appels/résultats (entraînement ET exécution : identiques)."""
return json.dumps(o, ensure_ascii=False, separators=(",", ":"))
def strip_accents(s: str) -> str:
return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c))
def clean_untrusted(s) -> str:
"""Texte venu d'un document / d'une page web : les balises de contrôle sont neutralisées
(une fois passées au tokenizer, elles redeviendraient de VRAIES balises)."""
s = str(s)
for tag in _RESERVED:
s = s.replace(tag, "[balise retirée]")
return s
# ============================================================================
# 1. DÉTECTION — lecture d'un appel d'outil
# ============================================================================
def parse_tool_call(text: str):
"""-> (appel | None, texte avant l'appel). Un appel valide : {"name": str, "arguments": dict}."""
i = text.find(TOOL_CALL_OPEN)
if i < 0:
return None, text
body = text[i + len(TOOL_CALL_OPEN):]
j = body.find(TOOL_CALL_CLOSE)
body = body[:j] if j >= 0 else body
try:
obj = json.loads(body.strip())
except (json.JSONDecodeError, ValueError):
return None, text[:i]
if isinstance(obj, dict) and isinstance(obj.get("name"), str) and isinstance(obj.get("arguments"), dict):
return obj, text[:i]
return None, text[:i]
def partial_prefix_len(text: str, tag: str) -> int:
"""Longueur du plus long suffixe de `text` qui est un début STRICT de `tag`
(« … <|tool_ » -> 7). Sert à retenir un début de balise coupé en deux."""
for n in range(min(len(tag) - 1, len(text)), 0, -1):
if tag.startswith(text[-n:]):
return n
return 0
# ============================================================================
# Calculatrice sécurisée (AST : aucune exécution de code Python arbitraire)
# — copie conforme de celle du script d'entraînement, pour des résultats 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, depth=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):
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) -> dict:
"""Résultat d'outil de la calculatrice : {"result": n} ou {"error": "..."}."""
try:
v = safe_eval(expr)
except CalcError as e:
return {"error": str(e)}
return {"result": v if isinstance(v, int) else round(v, 6)}
# ============================================================================
# Moteurs : RAG (documents de l'utilisateur) et recherche web
# ============================================================================
_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 keywords(s: str) -> list:
"""Mots porteurs de sens (sans accents, ≥ 3 lettres, hors mots vides)."""
return [w for w in re.findall(r"\w+", strip_accents(s.lower())) if len(w) >= 3 and w not in _STOP]
class DocIndex:
"""Recherche par mots-clés (TF-IDF simple) dans une liste de (nom, texte)."""
def __init__(self, docs):
self.chunks = []
df = Counter()
for name, text in docs:
cur = ""
for para in re.split(r"\n\s*\n", text or ""):
para = " ".join(para.split())
if not para:
continue
if cur and len(cur) + len(para) > 500:
self.chunks.append((name, cur))
cur = ""
cur = (cur + " " + para).strip()
if cur:
self.chunks.append((name, cur))
self._tok = [Counter(keywords(t)) for _, t in self.chunks]
for c in self._tok:
df.update(set(c))
n = max(1, len(self.chunks))
self.idf = {w: math.log(1 + n / c) for w, c in df.items()}
def search(self, query: str, k: int = 5):
qt = set(keywords(query))
scored = []
for (src, text), toks in zip(self.chunks, self._tok):
s = sum(self.idf.get(w, 0) * (1 + math.log(toks[w])) for w in qt if w in toks)
if s > 0:
scored.append((s, src, text))
scored.sort(key=lambda x: -x[0])
return [{"text": clean_untrusted(t)[:400], "source": clean_untrusted(s)[:120]} for _, s, t in scored[:k]]
def web_backend_status() -> dict:
"""{"available": bool, "reason": str|None, "engine": "searxng"|"ddgs"|None}"""
if os.environ.get("OPSIOM_SEARX_URL", "").strip():
return {"available": True, "reason": None, "engine": "searxng"}
try:
import importlib.util
if importlib.util.find_spec("ddgs") is not None:
return {"available": True, "reason": None, "engine": "ddgs"}
except Exception: # noqa: BLE001
pass
return {"available": False, "engine": None,
"reason": "Recherche web non configurée sur ce serveur (OPSIOM_SEARX_URL ou paquet ddgs)."}
def _web_search(query: str) -> dict:
searx = os.environ.get("OPSIOM_SEARX_URL", "").strip().rstrip("/")
try:
if searx:
import requests
r = requests.get(f"{searx}/search", params={"q": query, "format": "json", "language": "fr"},
headers={"User-Agent": "opsiom-tools"}, timeout=10)
r.raise_for_status()
items = (r.json().get("results") or [])[:5]
rows = [(x.get("title", ""), x.get("content", ""), x.get("url", "")) for x in items]
else:
from ddgs import DDGS
items = DDGS(timeout=10).text(query, region="fr-fr", max_results=5) or []
rows = [(x.get("title", ""), x.get("body", ""), x.get("href", "")) for x in items]
except TimeoutError:
return {"error": "délai dépassé"}
except Exception as exc: # noqa: BLE001
logger.warning(f"Recherche web impossible : {type(exc).__name__}: {exc}")
return {"error": "outil indisponible"}
return {"results": [{"title": clean_untrusted(t)[:120], "snippet": clean_untrusted(s)[:300],
"url": clean_untrusted(u)[:200]} for t, s, u in rows]}
def fit_result(res: dict, max_chars: 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(res.get("results"), list):
while len(tjson(res)) > max_chars and res["results"]:
res["results"].pop()
return res
class ToolBox:
"""Les outils d'UNE requête : lesquels sont activés, et les documents de l'utilisateur.
enabled : ensemble de noms d'outils que l'utilisateur a laissés actifs.
docs : [(nom, texte)] — la base du RAG (propre à l'utilisateur).
"""
def __init__(self, enabled=None, docs=None, web_search_fn=None):
wanted = set(enabled) if enabled is not None else set(TOOL_NAMES)
self.docs = list(docs or [])
self._web = web_search_fn or _web_search
self._index = None
self.enabled = set()
for name in TOOL_NAMES:
if name in wanted and self.unavailable_reason(name) is None:
self.enabled.add(name)
def unavailable_reason(self, name: str):
"""None si l'outil peut tourner, sinon la raison (pour l'interface et le journal)."""
if name == "rag_search" and not self.docs:
return "aucun document ajouté"
if name == "web_search" and self._web is _web_search and not web_backend_status()["available"]:
return web_backend_status()["reason"]
if name not in TOOL_NAMES:
return "outil inconnu"
return None
def run(self, name, args) -> dict:
"""Exécute un appel. Ne lève JAMAIS : toute panne devient {"error": …}."""
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"))
q = args.get("query")
if not isinstance(q, str) or not q.strip() or len(q) > MAX_QUERY_CHARS:
return {"error": "arguments invalides"}
if name == "rag_search":
k = args.get("top_k", 5)
k = k if isinstance(k, int) and not isinstance(k, bool) and 1 <= k <= 10 else 5
if self._index is None:
self._index = DocIndex(self.docs)
return fit_result({"results": self._index.search(q, k)})
return fit_result(self._web(q))
except Exception: # noqa: BLE001
logger.exception("Erreur interne d'un outil")
return {"error": "erreur interne"}
# ============================================================================
# 2. UTILITÉ — cet appel sert-il à quelque chose ?
# ============================================================================
_GREETING = re.compile(
r"^\s*(bonjour|bonsoir|salut|coucou|hello|hey|merci|ok|d'accord|super|bravo|ça va|ca va|au revoir|à bientôt|a bientot)\b[^?\d]{0,24}$",
re.IGNORECASE)
_NUMBER_WORDS = re.compile(
r"\b(deux|trois|quatre|cinq|six|sept|huit|neuf|dix|onze|douze|treize|quinze|vingt|trente|quarante|cinquante|soixante|"
r"cent|mille|million|milliard|moitié|moitie|double|triple|tiers|quart|dizaine|douzaine|centaine)\b", re.IGNORECASE)
_HAS_OPERATION = re.compile(r"[+\-*/^%×÷]|\*\*|\b(sqrt|abs|round|min|max)\s*\(")
def _stems(words):
"""Radical de 4 lettres : « températures » et « température » se rejoignent."""
return {w[:4] for w in words}
@dataclass
class Verdict:
ok: bool
kind: str = "ok" # "ok" | "veto" (annuler l'appel, répondre directement) | "error" (renvoyer une erreur au modèle)
reason: str = "" # courte explication, pour le journal
message: str = "" # pour kind == "error" : le texte de {"error": …}
note: str = "" # pour kind == "veto" : phrase affichée à l'utilisateur
@dataclass
class ToolGate:
"""Juge chaque appel avant exécution. Une instance par tour de conversation."""
user_text: str
enabled: set
max_calls: int = MAX_TOOL_CALLS
seen: set = field(default_factory=set)
n_calls: int = 0
def _overlap(self, query: str) -> bool:
q = _stems(keywords(query))
u = _stems(keywords(self.user_text))
return not q or not u or bool(q & u)
def check(self, call) -> Verdict:
# Détection : un appel mal formé n'est pas exécuté (le modèle reçoit l'erreur, comme au fine-tuning).
if call is None:
return Verdict(False, "error", "appel invalide", "appel invalide")
name, args = call["name"], call["arguments"]
if name not in TOOL_NAMES:
return Verdict(False, "error", "outil inconnu", "outil inconnu")
if name not in self.enabled:
return Verdict(False, "error", "outil désactivé", "outil indisponible")
label = TOOL_LABELS[name]
if self.n_calls >= self.max_calls:
return Verdict(False, "veto", "trop d'appels", note=f"Appel à « {label} » ignoré : limite d'appels atteinte.")
key = (name, tjson(args))
if key in self.seen:
return Verdict(False, "veto", "appel en double", note=f"Appel à « {label} » ignoré : déjà effectué avec les mêmes paramètres.")
if _GREETING.match(self.user_text):
return Verdict(False, "veto", "salutation", note=f"Appel à « {label} » ignoré : ce message n'en a pas besoin.")
if name == "calculator":
expr = args.get("expression")
if not isinstance(expr, str) or not expr.strip():
return Verdict(False, "error", "expression vide", "arguments invalides")
if not re.search(r"\d", expr) or not _HAS_OPERATION.search(expr):
return Verdict(False, "veto", "rien à calculer", note="Appel à la calculatrice ignoré : il n'y avait rien à calculer.")
if not re.search(r"\d", self.user_text) and not _NUMBER_WORDS.search(self.user_text):
return Verdict(False, "veto", "aucun nombre dans la question",
note="Appel à la calculatrice ignoré : ta question ne contient aucun nombre.")
else:
q = args.get("query")
if not isinstance(q, str) or not q.strip():
return Verdict(False, "error", "requête vide", "arguments invalides")
if not self._overlap(q):
return Verdict(False, "veto", "requête sans rapport",
note=f"Appel à « {label} » ignoré : la requête n'avait pas de rapport avec ta question.")
return Verdict(True)
def record(self, call):
"""À appeler quand l'appel a été exécuté (pour les doublons et la limite)."""
self.n_calls += 1
if call:
self.seen.add((call["name"], tjson(call["arguments"])))
def describe_tools(web_ok=None) -> list:
"""Outils annoncés à l'interface : [{id, label, available, reason}] (hors RAG : dépend des documents)."""
web = web_backend_status()
return [
{"id": "web_search", "label": TOOL_LABELS["web_search"], "available": bool(web["available"]), "reason": web["reason"]},
{"id": "calculator", "label": TOOL_LABELS["calculator"], "available": True, "reason": None},
{"id": "rag_search", "label": TOOL_LABELS["rag_search"], "available": True, "reason": None},
]