Download modes.py from JuloEco/Opsiom: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/spaces/JuloEco/Opsiom/resolve/main/modes.py
- Command line
-
hf download hf://spaces/JuloEco/Opsiom/modes.py
-
curl -L -o modes.py https://huggingface.co/spaces/JuloEco/Opsiom/resolve/main/modes.py
15.2 kB
| # ============================================================================ | |
| # Opsiom Kaïro — les trois modes de génération : chat, raisonnement, agent | |
| # | |
| # chat <|Utilisateur|>\n{q}\n<|Assistant|>\n -> réponse directe | |
| # reasoning … -> <reasoning>\n…\n</reasoning>\n{réponse} (modèle phase 2) | |
| # agent … -> <|tool_call|>{…}<|/tool_call|> [le serveur exécute et | |
| # injecte <|tool_result|>{…}<|/tool_result|>] -> réponse (phase 3) | |
| # | |
| # Les balises sont du TEXTE ordinaire (le tokenizer 32k n'a que <pad>/<unk>/<bos>/<eos>) : | |
| # la détection se fait donc sur le texte décodé. Ce module ne dépend que de torch et de | |
| # tools.py (pas d'inference.py : il est testable avec un faux modèle, tests/test_modes.py). | |
| # | |
| # generate(...) est un générateur d'évènements : | |
| # ("token", "texte") texte à afficher (ET à enregistrer : c'est le transcript brut, | |
| # balises comprises ; l'interface le met en forme) | |
| # ("note", {"text": …}) remarque pour l'utilisateur (appel d'outil inutile ignoré…) | |
| # ("stats", {…}) en dernier : tokens consommés, outils utilisés, etc. | |
| # | |
| # Ce que ce module garantit pour l'agent : | |
| # - un appel n'est JAMAIS montré avant d'être validé (le texte est retenu entre | |
| # <|tool_call|> et <|/tool_call|>) ; s'il est jugé inutile (ToolGate), il est effacé | |
| # — le cache KV est ramené à l'état d'avant l'appel — puis le modèle doit répondre | |
| # directement (les tokens qui commencent par « < » sont interdits au premier pas) ; | |
| # - le résultat d'un outil est réinjecté tel qu'au fine-tuning, sans dépasser le contexte ; | |
| # - jamais plus de MAX_TOOL_CALLS appels par question. | |
| # ============================================================================ | |
| import logging | |
| import time | |
| from dataclasses import dataclass | |
| import torch | |
| from tools import (ASSISTANT_TAG, REASONING_CLOSE, REASONING_OPEN, TOOL_CALL_CLOSE, TOOL_CALL_OPEN, TOOL_RES_CLOSE, | |
| TOOL_RES_OPEN, USER_TAG, ToolGate, parse_tool_call, partial_prefix_len, tjson) | |
| logger = logging.getLogger("opsiom_frontend.modes") | |
| MODE_IDS = ("chat", "reasoning", "agent") | |
| ANSWER_RESERVE = 96 # tokens gardés libres pour la réponse après un résultat d'outil | |
| PROMPT_RESERVE = 64 # place minimale laissée après le prompt | |
| _STOP_TAGS = (USER_TAG, ASSISTANT_TAG, "<|endoftext|>") | |
| class GenConfig: | |
| max_new: int = 200 # budget de la RÉPONSE (ou d'un segment, en mode agent) | |
| temperature: float = 0.7 | |
| top_k: int = 40 | |
| top_p: float = 0.9 | |
| repetition_penalty: float = 1.3 | |
| reasoning_budget: int = 400 # tokens supplémentaires accordés au raisonnement | |
| max_calls: int = 4 | |
| class ContextFull(Exception): | |
| """Le contexte du modèle (max_seq_len) est plein.""" | |
| # ============================================================================ | |
| # Échantillonnage (même logique que ModernLLM._sample_next_token) | |
| # ============================================================================ | |
| def sample_next(logits, cfg: GenConfig, generated_ids=None): | |
| """logits : tensor (1, V). Renvoie l'id (int) du token suivant.""" | |
| rp = cfg.repetition_penalty | |
| if rp != 1.0 and generated_ids: | |
| uniq = torch.unique(torch.tensor(generated_ids, dtype=torch.long, device=logits.device)) | |
| uniq = uniq[uniq < logits.size(-1)] | |
| if uniq.numel() > 0: | |
| prev = logits[0, uniq] | |
| logits[0, uniq] = torch.where(prev > 0, prev / rp, prev * rp) | |
| if cfg.temperature <= 0.0: | |
| return int(torch.argmax(logits, dim=-1)) | |
| logits = logits / cfg.temperature | |
| if cfg.top_k and cfg.top_k > 0: | |
| kth = torch.topk(logits, min(cfg.top_k, logits.size(-1)))[0][:, [-1]] | |
| logits = torch.where(logits < kth, torch.full_like(logits, float("-inf")), logits) | |
| probs = torch.softmax(logits, dim=-1) | |
| if cfg.top_p is not None and cfg.top_p < 1.0: | |
| sp, si = torch.sort(probs, descending=True, dim=-1) | |
| cum = torch.cumsum(sp, dim=-1) | |
| sp[cum - sp > cfg.top_p] = 0.0 | |
| sp = sp / sp.sum(dim=-1, keepdim=True) | |
| probs = torch.zeros_like(probs).scatter_(-1, si, sp) | |
| return int(torch.multinomial(probs, num_samples=1)) | |
| # ============================================================================ | |
| # Session : un contexte avec cache KV, qu'on peut prolonger et ramener en arrière | |
| # ============================================================================ | |
| class Session: | |
| def __init__(self, model): | |
| self.model = model | |
| self.max_len = int(model.args.max_seq_len) | |
| self.kv = [(None, None)] * int(model.args.n_layers) | |
| self.ids: list = [] | |
| self.logits = None | |
| def pos(self) -> int: | |
| return len(self.ids) | |
| def feed(self, new_ids): | |
| if not new_ids: | |
| return | |
| if self.pos + len(new_ids) > self.max_len: | |
| raise ContextFull() | |
| self.model.eval() | |
| device = next(self.model.parameters()).device | |
| x = torch.tensor([list(new_ids)], dtype=torch.long, device=device) | |
| logits, self.kv = self.model.forward(x, kv_caches=self.kv, start_pos=self.pos) | |
| self.logits = logits[:, -1, :] | |
| self.ids = self.ids + list(new_ids) | |
| def snapshot(self): | |
| return (self.pos, None if self.logits is None else self.logits.clone()) | |
| def restore(self, snap): | |
| n, logits = snap | |
| self.kv = [(k[:, :, :n], v[:, :, :n]) if k is not None else (None, None) for k, v in self.kv] | |
| self.ids = self.ids[:n] | |
| self.logits = logits | |
| _LT_CACHE = {} | |
| def lt_token_ids(tok, vocab_size: int) -> list: | |
| """Ids des tokens dont le texte commence par « < » (début possible d'une balise).""" | |
| key = id(tok) | |
| if key not in _LT_CACHE: | |
| ids = [] | |
| for i in range(vocab_size): | |
| try: | |
| if tok.decode([i]).lstrip().startswith("<"): | |
| ids.append(i) | |
| except Exception: # noqa: BLE001 | |
| continue | |
| _LT_CACHE[key] = ids | |
| return _LT_CACHE[key] | |
| # ============================================================================ | |
| # Un segment de génération (jusqu'à <eos>, une fin d'appel d'outil, ou le budget) | |
| # ============================================================================ | |
| class Segment: | |
| reason: str = "max" # eos | call | max | context | |
| text: str = "" # texte décodé du segment (appel compris) | |
| shown: int = 0 # caractères déjà émis | |
| n_tokens: int = 0 | |
| forced_close: bool = False | |
| forbidden_call: bool = False | |
| def _trim_incomplete(text: str, end: int) -> int: | |
| """Recule `end` d'un caractère de remplacement « � » (caractère multi-octets incomplet).""" | |
| while end > 0 and text[end - 1] == "�": | |
| end -= 1 | |
| return end | |
| def run_segment(sess: Session, tok, cfg: GenConfig, *, max_new, detect_calls=False, forbid_call=False, | |
| ban_ids=None, reasoning_cap=0): | |
| """Générateur : émet ("text", delta) ; renvoie un Segment (via `yield from`).""" | |
| seg = Segment() | |
| ids: list = [] | |
| limit = max_new + (reasoning_cap or 0) | |
| reasoning_closed = False | |
| step = 0 | |
| text = "" | |
| ban = None | |
| if ban_ids: | |
| ban = torch.tensor(list(ban_ids), dtype=torch.long) | |
| while True: | |
| if step >= limit: | |
| seg.reason = "max" | |
| break | |
| if sess.pos >= sess.max_len - 1: | |
| seg.reason = "context" | |
| break | |
| logits = sess.logits.clone() | |
| if step == 0 and ban is not None: | |
| logits[:, ban[ban < logits.size(-1)]] = float("-inf") | |
| nxt = sample_next(logits, cfg, ids) | |
| if nxt == tok.eot_token: | |
| seg.reason = "eos" | |
| break | |
| ids.append(nxt) | |
| try: | |
| sess.feed([nxt]) | |
| except ContextFull: | |
| seg.reason = "context" | |
| break | |
| step += 1 | |
| text = tok.decode(ids) | |
| # Le modèle se met à écrire le tour suivant de la conversation : on s'arrête là. | |
| cut = min([text.find(t) for t in _STOP_TAGS if t in text] or [-1]) | |
| if cut >= 0: | |
| text = text[:cut] | |
| seg.reason = "eos" | |
| break | |
| # Un début de balise coupé en deux (« <|Utili ») est retenu : il ne doit jamais s'afficher. | |
| held_tags = _STOP_TAGS + ((TOOL_CALL_OPEN,) if (detect_calls or forbid_call) else ()) | |
| visible_end = len(text) - max(partial_prefix_len(text, t) for t in held_tags) | |
| if detect_calls or forbid_call: | |
| i = text.find(TOOL_CALL_OPEN) | |
| if i >= 0: | |
| if forbid_call: | |
| text = text[:i] | |
| seg.reason, seg.forbidden_call = "eos", True | |
| break | |
| j = text.find(TOOL_CALL_CLOSE, i) | |
| if j >= 0: | |
| text = text[:j + len(TOOL_CALL_CLOSE)] | |
| seg.reason = "call" | |
| break | |
| visible_end = i # appel en cours d'écriture : on retient tout | |
| visible_end = _trim_incomplete(text, visible_end) | |
| if visible_end > seg.shown: | |
| yield ("text", text[seg.shown:visible_end]) | |
| seg.shown = visible_end | |
| # Raisonnement : ferme-le de force s'il dépasse son budget, pour toujours obtenir une réponse. | |
| if reasoning_cap: | |
| ro = text.rfind(REASONING_OPEN) | |
| if ro >= 0: | |
| if REASONING_CLOSE in text[ro:]: | |
| if not reasoning_closed: | |
| reasoning_closed = True | |
| limit = min(limit, step + max_new) | |
| elif step >= reasoning_cap and not seg.forced_close: | |
| inj = tok.encode("\n" + REASONING_CLOSE + "\n") | |
| try: | |
| sess.feed(inj) | |
| except ContextFull: | |
| seg.reason = "context" | |
| break | |
| ids += inj | |
| text = tok.decode(ids) | |
| seg.forced_close = True | |
| limit = step + max_new | |
| yield ("text", text[seg.shown:]) | |
| seg.shown = len(text) | |
| seg.n_tokens = len(ids) | |
| if seg.reason != "call": | |
| if detect_calls and TOOL_CALL_OPEN in text: | |
| text = text[:text.find(TOOL_CALL_OPEN)] # appel resté ouvert : on l'abandonne | |
| if len(text) > seg.shown: | |
| yield ("text", text[seg.shown:]) | |
| seg.shown = len(text) | |
| seg.text = text | |
| return seg | |
| # ============================================================================ | |
| # Orchestration | |
| # ============================================================================ | |
| def _wrap_result(result) -> str: | |
| return "\n" + TOOL_RES_OPEN + tjson(result) + TOOL_RES_CLOSE + "\n" | |
| def _fit_injection(tok, result, room: int): | |
| """Résultat d'outil encodé, réduit pour tenir dans `room` tokens. -> (texte, ids) ou None.""" | |
| for _ in range(64): | |
| text = _wrap_result(result) | |
| ids = tok.encode(text) | |
| if len(ids) <= room: | |
| return text, ids, result | |
| if isinstance(result, dict) and isinstance(result.get("results"), list) and result["results"]: | |
| result["results"].pop() | |
| else: | |
| break | |
| result = {"error": "résultat trop volumineux"} | |
| text = _wrap_result(result) | |
| ids = tok.encode(text) | |
| return (text, ids, result) if len(ids) <= room else None | |
| def _agent(sess, tok, cfg, toolbox, user_text, stats): | |
| ban = lt_token_ids(tok, int(getattr(tok, "vocab_size", 0) or 0)) | |
| gate = ToolGate(user_text=user_text, enabled=set(toolbox.enabled), max_calls=cfg.max_calls) | |
| direct_next = False | |
| while True: | |
| forbid = direct_next or gate.n_calls >= gate.max_calls | |
| snap = sess.snapshot() | |
| seg = yield from run_segment(sess, tok, cfg, max_new=cfg.max_new, detect_calls=True, | |
| forbid_call=forbid, ban_ids=ban if forbid else None) | |
| direct_next = False | |
| if seg.reason != "call": | |
| if seg.reason == "context": | |
| stats["truncated"] = True | |
| break | |
| call, _before = parse_tool_call(seg.text) | |
| verdict = gate.check(call) | |
| if verdict.kind == "veto" and seg.shown == 0: | |
| # Appel inutile : on l'efface (rien n'a été montré), on revient à l'état d'avant, et le | |
| # modèle doit répondre directement. | |
| sess.restore(snap) | |
| stats["vetoes"] += 1 | |
| logger.info(f"Appel d'outil annulé ({verdict.reason}) : {tjson(call) if call else seg.text[:80]}") | |
| yield ("note", {"kind": "veto", "tool": call["name"] if call else None, "text": verdict.note}) | |
| direct_next = True | |
| continue | |
| # L'appel est accepté (ou doit recevoir une erreur) : on le montre, puis on exécute. | |
| yield ("text", seg.text[seg.shown:]) | |
| t0 = time.time() | |
| if verdict.ok: | |
| result = toolbox.run(call["name"], call["arguments"]) | |
| gate.record(call) | |
| elif verdict.kind == "veto": | |
| result = {"error": "outil indisponible"} # appel inutile mais déjà affiché | |
| gate.record(call) | |
| else: | |
| result = {"error": verdict.message} | |
| gate.record(call) | |
| ms = int((time.time() - t0) * 1000) | |
| stats["tools"].append({"name": call["name"] if call else None, "ok": "error" not in result, "ms": ms}) | |
| room = sess.max_len - 1 - sess.pos - ANSWER_RESERVE | |
| fitted = _fit_injection(tok, result, room) | |
| if fitted is None: | |
| stats["truncated"] = True | |
| break | |
| inj_text, inj_ids, _ = fitted | |
| try: | |
| sess.feed(inj_ids) | |
| except ContextFull: | |
| stats["truncated"] = True | |
| break | |
| yield ("text", inj_text) | |
| def generate(mode, model, tok, prompt, cfg: GenConfig, toolbox=None, user_text="", use_bos=False): | |
| """Générateur d'évènements pour UNE réponse (voir l'en-tête du module).""" | |
| sess = Session(model) | |
| prompt_ids = list(tok.encode(prompt)) | |
| if use_bos and getattr(tok, "bos_token", None) is not None: | |
| prompt_ids = [tok.bos_token] + prompt_ids | |
| keep = sess.max_len - PROMPT_RESERVE | |
| if len(prompt_ids) > keep: | |
| prompt_ids = prompt_ids[-keep:] | |
| sess.feed(prompt_ids) | |
| stats = {"mode": mode, "tools": [], "vetoes": 0, "forced_close": False, "truncated": False} | |
| if mode == "agent" and toolbox is not None: | |
| yield from _agent(sess, tok, cfg, toolbox, user_text, stats) | |
| elif mode == "reasoning": | |
| seg = yield from run_segment(sess, tok, cfg, max_new=cfg.max_new, reasoning_cap=cfg.reasoning_budget) | |
| stats["forced_close"] = seg.forced_close | |
| stats["truncated"] = seg.reason in ("max", "context") | |
| else: | |
| seg = yield from run_segment(sess, tok, cfg, max_new=cfg.max_new) | |
| stats["truncated"] = seg.reason in ("max", "context") | |
| stats["tokens"] = len(sess.ids) | |
| yield ("stats", stats) | |