import os import threading import time from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel REPO = os.getenv("MODEL_REPO", "Qwen/Qwen2.5-1.5B-Instruct-GGUF") FILE = os.getenv("MODEL_FILE", "qwen2.5-1.5b-instruct-q4_k_m.gguf") KEY = os.getenv("API_KEY", "") CTX = int(os.getenv("CTX", "6144")) THREADS = int(os.getenv("THREADS", str(os.cpu_count() or 2))) app = FastAPI() state = {"llm": None, "error": None, "since": time.time()} lock = threading.Lock() def load(): try: from huggingface_hub import hf_hub_download from llama_cpp import Llama, LlamaRAMCache path = hf_hub_download(REPO, FILE) llm = Llama(model_path=path, n_ctx=CTX, n_threads=THREADS, n_batch=512, verbose=False) llm.set_cache(LlamaRAMCache(capacity_bytes=1 << 30)) state["llm"] = llm except Exception as e: state["error"] = str(e)[:500] threading.Thread(target=load, daemon=True).start() class Msg(BaseModel): role: str content: str class Req(BaseModel): messages: list[Msg] max_tokens: int = 500 temperature: float = 0.2 @app.get("/") def root(): return {"ok": True, "ready": state["llm"] is not None, "error": state["error"], "model": f"{REPO}/{FILE}"} @app.post("/chat") def chat(r: Req, x_key: str = Header(default="")): if not KEY or x_key != KEY: raise HTTPException(401, "Falscher Schlüssel") if state["llm"] is None: raise HTTPException(503, state["error"] or "Modell lädt noch") msgs = [{"role": m.role if m.role in ("system", "user", "assistant") else "user", "content": m.content[:12000]} for m in r.messages][-16:] if "qwen3" in FILE.lower() and msgs and msgs[-1]["role"] == "user": msgs[-1]["content"] += " /no_think" t0 = time.time() with lock: out = state["llm"].create_chat_completion(messages=msgs, max_tokens=max(32, min(900, r.max_tokens)), temperature=max(0.0, min(1.0, r.temperature)), top_p=0.9, repeat_penalty=1.08) text = out["choices"][0]["message"]["content"] or "" if "" in text: text = text.split("", 1)[1] return {"reply": text.strip(), "usage": out.get("usage"), "ms": int((time.time() - t0) * 1000)}