Download core/llm_engine.py from RDS777/SKKAI: direct link, hf CLI and curl.
- Browser
- Download file 4.03 kB
-
https://huggingface.co/spaces/RDS777/SKKAI/resolve/main/core/llm_engine.py
- Command line
-
hf download hf://spaces/RDS777/SKKAI/core/llm_engine.py
-
curl -L -o llm_engine.py https://huggingface.co/spaces/RDS777/SKKAI/resolve/main/core/llm_engine.py
4.03 kB
| import json | |
| import os | |
| import threading | |
| import time | |
| from typing import Optional | |
| from huggingface_hub import hf_hub_download | |
| from llama_cpp import Llama, LlamaGrammar | |
| MODEL_REPO = os.environ.get("MODEL_REPO", "Qwen/Qwen2.5-0.5B-Instruct-GGUF") | |
| MODEL_FILE = os.environ.get("MODEL_FILE", "qwen2.5-0.5b-instruct-q4_k_m.gguf") | |
| N_THREADS = int(os.environ.get("LLM_THREADS", "2")) | |
| PLAN_GBNF = r''' | |
| root ::= "{" ws "\"task_ids\"" ws ":" ws "[" ws (num (ws "," ws num){0,2})? ws "]" ws "," ws "\"reasoning\"" ws ":" ws str ws "}" | |
| num ::= [0-9]{1,4} | |
| str ::= "\"" [^"\\\n]{0,160} "\"" | |
| ws ::= " "? | |
| ''' | |
| SYSTEM_PROMPT = ( | |
| "Tu es le CEO d'une entreprise d'ingénierie. Un module d'analyse silencieux (Oracle) " | |
| "te fournit des scores numériques. Tu ne calcules pas, tu choisis les tâches à lancer " | |
| "ce cycle en t'appuyant sur ces scores. Tu réponds UNIQUEMENT par un JSON de la forme " | |
| '{"task_ids": [ids], "reasoning": "une phrase courte en français"}.' | |
| ) | |
| class SkyCEO: | |
| def __init__(self): | |
| self.llm: Optional[Llama] = None | |
| self.grammar: Optional[LlamaGrammar] = None | |
| self.status = "loading" | |
| self.error: Optional[str] = None | |
| self._infer_lock = threading.Lock() | |
| def load(self) -> None: | |
| try: | |
| self.status = "loading" | |
| path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE) | |
| self.llm = Llama( | |
| model_path=path, | |
| n_ctx=2048, | |
| n_threads=N_THREADS, | |
| verbose=False, | |
| ) | |
| self.grammar = LlamaGrammar.from_string(PLAN_GBNF) | |
| self.status = "ready" | |
| print("[llm] modèle prêt", flush=True) | |
| except Exception as e: | |
| self.status = "failed" | |
| self.error = str(e) | |
| print(f"[llm] échec de chargement: {e}", flush=True) | |
| def generate_plan(self, oracle_metrics: dict, feedback: Optional[str] = None) -> dict: | |
| if self.status != "ready" or self.llm is None: | |
| raise RuntimeError("Modèle non prêt") | |
| valid_ids = [t["id"] for t in oracle_metrics.get("tasks", [])] | |
| feasible = oracle_metrics.get("feasible_set", []) | |
| budget = oracle_metrics.get("budget_usd") | |
| compact = { | |
| "market_risk": oracle_metrics.get("market_risk"), | |
| "budget_usd": budget, | |
| "tasks": [ | |
| { | |
| "id": t["id"], | |
| "score": t.get("score"), | |
| "cost": t.get("cost"), | |
| "revenue": t.get("revenue"), | |
| } | |
| for t in oracle_metrics.get("tasks", []) | |
| ], | |
| } | |
| user = ( | |
| f"Métriques de l'Oracle : {json.dumps(compact, ensure_ascii=False)}\n" | |
| f"IDs de tâches valides : {valid_ids}\n" | |
| f"Budget disponible : {budget}\n" | |
| f"Ensemble réalisable recommandé (feasible_set) : {feasible}\n" | |
| "Règles : 3 tâches maximum ; coût total inférieur ou égal au budget ; " | |
| "IDs uniquement parmi la liste valide. Reprends de préférence le feasible_set." | |
| ) | |
| if feedback: | |
| user += ( | |
| f"\nTon plan précédent a été rejeté par le CFO : {feedback} " | |
| f"Propose un plan différent, par exemple {feasible}." | |
| ) | |
| t0 = time.time() | |
| with self._infer_lock: | |
| out = self.llm.create_chat_completion( | |
| messages=[ | |
| {"role": "system", "content": SYSTEM_PROMPT}, | |
| {"role": "user", "content": user}, | |
| ], | |
| grammar=self.grammar, | |
| max_tokens=200, | |
| temperature=0.1, | |
| ) | |
| print(f"[llm] inférence {time.time() - t0:.1f}s, prompt={len(user)} caractères", flush=True) | |
| content = out["choices"][0]["message"]["content"] | |
| try: | |
| return json.loads(content) | |
| except Exception: | |
| return {"_raw": content} |