Download headless_api.py from RDS777/allin1: direct link, hf CLI and curl.
- Browser
- Download file 5.22 kB
-
https://huggingface.co/spaces/RDS777/allin1/resolve/main/headless_api.py
- Command line
-
hf download hf://spaces/RDS777/allin1/headless_api.py
-
curl -L -o headless_api.py https://huggingface.co/spaces/RDS777/allin1/resolve/main/headless_api.py
5.22 kB
| """API headless (CI/CD, cron, webhook) : POST /api/run -> job_id ; GET /api/jobs/{id} ; Bearer SKY_API_KEY. | |
| Un seul worker : les jobs s'exécutent l'un après l'autre et partagent le verrou de l'UI. | |
| """ | |
| from __future__ import annotations | |
| import hmac | |
| import queue | |
| import threading | |
| import time | |
| import uuid | |
| from collections import OrderedDict | |
| from fastapi import Depends, FastAPI, Header, HTTPException | |
| from pydantic import BaseModel, Field | |
| import runtime | |
| MAX_JOBS, MAX_QUEUE, MAX_LOG_LINES = 50, 10, 400 | |
| class RunRequest(BaseModel): | |
| task: str = Field(min_length=3, max_length=4000) | |
| mode: str = Field(default="full", pattern="^(full|plan)$") | |
| class JobManager: | |
| def __init__(self) -> None: | |
| self.jobs: "OrderedDict[str, dict]" = OrderedDict() | |
| self.q: queue.Queue = queue.Queue(maxsize=MAX_QUEUE) | |
| self._lock = threading.Lock() | |
| self._worker = None | |
| def _ensure_worker(self) -> None: | |
| with self._lock: | |
| if self._worker is None: | |
| self._worker = threading.Thread(target=self._loop, daemon=True) | |
| self._worker.start() | |
| def submit(self, task: str, mode: str) -> str: | |
| self._ensure_worker() | |
| job_id = uuid.uuid4().hex[:12] | |
| job = {"id": job_id, "task": task, "mode": mode, "status": "queued", "created": time.time(), | |
| "logs": [], "result": None} | |
| try: | |
| self.q.put_nowait(job_id) | |
| except queue.Full: | |
| raise HTTPException(429, "file d'attente pleine") | |
| with self._lock: | |
| self.jobs[job_id] = job | |
| while len(self.jobs) > MAX_JOBS: | |
| self.jobs.popitem(last=False) | |
| return job_id | |
| def get(self, job_id: str): | |
| return self.jobs.get(job_id) | |
| def cancel(self, job_id: str) -> bool: | |
| job = self.jobs.get(job_id) | |
| if not job: | |
| return False | |
| if job["status"] == "queued": | |
| job["status"] = "cancelled" | |
| elif job["status"] == "running": | |
| runtime.STOP.set() | |
| return True | |
| def _loop(self) -> None: | |
| while True: | |
| job = self.jobs.get(self.q.get()) | |
| if not job or job["status"] != "queued": | |
| continue | |
| with runtime.RUN_LOCK: | |
| err = runtime.precheck() | |
| if err: | |
| job.update(status="error", result={"error": err}) | |
| continue | |
| job["status"] = "running" | |
| runtime.STOP.clear() | |
| try: | |
| for ev in runtime.state["agent"].run_task(job["task"], runtime.WS, runtime.STOP.is_set, job["mode"]): | |
| if ev.kind == "done": | |
| r = ev.result | |
| try: | |
| cid = runtime.DB.add_cycle(job["task"], r) | |
| except Exception as e: # le journal ne doit pas faire échouer le job | |
| print(f"[DB] add_cycle : {e!r}", flush=True) | |
| cid = None | |
| job["result"] = {"cycle_id": cid, "success": r.success, "stop_reason": r.stop_reason, | |
| "attempts": r.attempts, "duration_s": r.duration_s, "plan": r.plan, | |
| "diff": r.diff, "tokens_in": r.tokens_in, "tokens_out": r.tokens_out, | |
| "tok_per_s": r.tok_per_s} | |
| elif ev.kind != "progress": | |
| job["logs"].append(f"{ev.kind}: {ev.text[:500]}") | |
| del job["logs"][:-MAX_LOG_LINES] | |
| r = job["result"] or {} | |
| job["status"] = "succeeded" if r.get("success") or job["mode"] == "plan" else "failed" | |
| except Exception as e: | |
| job.update(status="error", result={"error": repr(e)}) | |
| manager = JobManager() | |
| app = FastAPI(title="SKY Agent API", docs_url=None, redoc_url=None) | |
| def require_auth(authorization: str = Header(default="")) -> None: | |
| if not runtime.AUTH_ON: | |
| if runtime.ALLOW_ANON: | |
| return | |
| raise HTTPException(503, "SKY_API_KEY non défini : API désactivée") | |
| token = authorization.removeprefix("Bearer ").strip() | |
| if not hmac.compare_digest(token.encode(), runtime.API_KEY.encode()): | |
| raise HTTPException(401, "token invalide") | |
| def health() -> dict: | |
| return {"status": "ok", "model": runtime.state["status"]} | |
| def run(req: RunRequest) -> dict: | |
| return {"job_id": manager.submit(req.task, req.mode), "status": "queued"} | |
| def job_status(job_id: str) -> dict: | |
| job = manager.get(job_id) | |
| if not job: | |
| raise HTTPException(404, "job inconnu") | |
| return {**job, "logs": job["logs"][-100:]} | |
| def job_cancel(job_id: str) -> dict: | |
| if not manager.cancel(job_id): | |
| raise HTTPException(404, "job inconnu") | |
| return {"status": "cancel_requested"} | |