Black Goku commited on
Update app.py
Browse files1 unmodified line234567891011121314153 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485863 unmodified lines9091929394959697989910010110210391 unmodified lines1951961971981992002012022032042052 unmodified lines2082092102112122132141 unmodified line21621721821922022122210 unmodified lines23323423523623723823924024124224324424524624724824925025125279 unmodified lines33233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137224 unmodified lines3973983994004014024031 unmodified lineYappy - AI motivation/discipline/support chatbot backendCreated by RikServes Qwen2.5-3B-Instruct (GGUF, CPU) via llama-cpp-python, streamed overServer-Sent Events.STATELESS BY DESIGN: this server keeps no conversation memory of its own.The frontend stores chat history in the browser's localStorage (per mode)and sends the relevant history back with every request. This means chathistory survives Space sleep/restarts, since it never depended on theserver remembering anything."""import os3 unmodified linesfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel, Fieldfrom sse_starlette.sse import EventSourceResponsefrom huggingface_hub import hf_hub_downloadfrom llama_cpp import Llamaimport threading# ---------------------------------------------------------------------------# Config# ---------------------------------------------------------------------------MODEL_REPO = os.environ.get("MODEL_REPO", "Qwen/Qwen2.5-3B-Instruct-GGUF")MODEL_FILE = os.environ.get("MODEL_FILE", "qwen2.5-3b-instruct-q4_k_m.gguf")MODEL_DIR = os.environ.get("MODEL_DIR", "/app/models")# Context window. Kept smaller than the model's max (32k) since we only# send a short recent history per request now - a smaller n_ctx means# less memory/CPU overhead per request on free hardware.N_CTX = int(os.environ.get("N_CTX", "3072"))# Max tokens the model is allowed to generate per reply (thinking block +# answer combined). Kept deliberately short on free CPU so replies finish# well within Vercel's serverless timeout window instead of getting cut# off by the platform mid-generation.MAX_NEW_TOKENS = int(os.environ.get("MAX_NEW_TOKENS", "350"))N_THREADS = int(os.environ.get("N_THREADS", str(os.cpu_count() or 4)))# Simple shared-secret auth so randoms can't hammer your Space directly.# Set this as a Secret in the HF Space, and send it as a header from Vercel.API_KEY = os.environ.get("YAPPY_API_KEY", "")# How many past turns (from client-supplied history) we'll actually feed# back into the model per request. Kept small on CPU: a longer prompt# takes longer to process before the model even starts generating.MAX_HISTORY_MESSAGES = int(os.environ.get("MAX_HISTORY_MESSAGES", "10"))# ---------------------------------------------------------------------------# Model loading# ---------------------------------------------------------------------------os.makedirs(MODEL_DIR, exist_ok=True)print(f"[Yappy] Downloading/locating model {MODEL_REPO}/{MODEL_FILE} ...")model_path = hf_hub_download(repo_id=MODEL_REPO,filename=MODEL_FILE,local_dir=MODEL_DIR,)print(f"[Yappy] Model ready at {model_path}")print("[Yappy] Loading model into llama.cpp ...")llm = Llama(model_path=model_path,n_ctx=N_CTX,n_threads=N_THREADS,n_gpu_layers=0, # CPU-only free Spacechat_format="chatml",verbose=False,)print("[Yappy] Model loaded. Ready to yap.")# A lock because llama-cpp-python's Llama object is not safely# re-entrant across concurrent requests on a single instance.model_lock = threading.Lock()# ---------------------------------------------------------------------------# Mode system prompts3 unmodified lines"You are Yappy, an AI companion created by Rik. You are not a generic ""assistant - you have a distinct personality that adapts to the mode ""the user picked, but you always remember you are Yappy. Keep replies ""SHORT - 2 to 4 sentences, like texting a person, never a long essay. ""Never use markdown headers or bullet-point lists unless the user ""explicitly asks for one.\n\n""Before every reply, think first in <thinking>...</thinking> tags - ""1-2 short sentences only on what angle/tone fits. Then immediately ""after </thinking>, write your short reply as plain text, no other ""tags. Always include both parts, but keep both very brief - token ""budget is limited, so get straight to the point.")MODE_PROMPTS = {91 unmodified lines# App# ---------------------------------------------------------------------------app = FastAPI(title="Yappy API", version="2.1.0")app.add_middleware(CORSMiddleware,allow_origins=["*"], # tighten to your Vercel domain once deployedallow_credentials=True,allow_methods=["*"],allow_headers=["*"],2 unmodified linesdef check_auth(request: Request):if not API_KEY:return # no key configured -> auth disabled (fine for testing)sent = request.headers.get("x-api-key", "")if sent != API_KEY:raise HTTPException(status_code=401, detail="Invalid or missing API key")1 unmodified line@app.get("/")def root():return {"status": "ok", "service": "Yappy", "model": MODEL_FILE, "mode": "stateless"}@app.get("/health")10 unmodified linesclass ThinkingSplitter:"""Consumes raw model tokens one chunk at a time and yields SSE events,routing text to 'thinking' or 'token' (answer) depending on whetherwe're currently inside a <thinking>...</thinking> block. Handles tagboundaries that land awkwardly across separate token chunks bybuffering a small tail of text whenever a partial tag might be forming."""def __init__(self):self.buffer = ""self.in_thinking = Falseself.seen_thinking_open = Falseself.full_raw = "" # everything the model produced, unmodifiedself.answer_only = "" # just the post-</thinking> reply textdef _maybe_partial_tag_tail(self, text: str) -> str:max_tag_len = max(len(THINK_OPEN), len(THINK_CLOSE))79 unmodified linesdef _generate_stream(mode: str, history: List[HistoryTurn], user_message: str, profile: Dict):"""Generator that yields SSE-formatted chunks as the model streams.Splits the model's <thinking> block from its real answer and yieldsthem as separate event types ('thinking' vs 'token'). Stateless -takes the full conversation as input, keeps nothing afterward."""messages = _build_messages(mode, history, user_message, profile)splitter = ThinkingSplitter()with model_lock:stream = llm.create_chat_completion(messages=messages,max_tokens=MAX_NEW_TOKENS,temperature=0.85,top_p=0.95,stream=True,)for chunk in stream:choice = chunk["choices"][0]delta = choice.get("delta", {})token = delta.get("content", "")if token:for event in splitter.feed(token):yield event# NOTE: no auto-continue pass here on purpose. On free CPU, a# second generation call would roughly double worst-case latency,# which risks exceeding Vercel's serverless timeout. Since# MAX_NEW_TOKENS is now tuned to be short enough that replies# normally finish naturally, an occasional mid-sentence cutoff is# an acceptable trade-off for reliability.for event in splitter.flush():yield eventyield {"event": "done", "data": ""}24 unmodified lines@app.post("/chat")def chat_once(payload: ChatRequest, request: Request):"""Non-streaming fallback endpoint."""check_auth(request)if not payload.message or not payload.message.strip():1 unmodified line23456789101112131415163 unmodified lines20212223242526272829303132333435363738393 unmodified lines434445464748495051525354555691 unmodified lines1481491501511521531541551561571582 unmodified lines1611621631641651661671 unmodified line16917017117217317417510 unmodified lines18618718818919019119219319419519619779 unmodified lines27727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231324 unmodified lines3383393403413423431 unmodified lineYappy - AI motivation/discipline/support chatbot backendCreated by RikUses Hugging Face's hosted Inference API (via huggingface_hub'sInferenceClient) rather than running a model locally on the Space's ownCPU. This avoids overloading the free CPU Space - the actual generationhappens on HF's shared inference infrastructure, and this Space justproxies the request and streams the response back.STATELESS BY DESIGN: this server keeps no conversation memory of its own.The frontend stores chat history in the browser's localStorage (per mode)and sends the relevant history back with every request."""import os3 unmodified linesfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel, Fieldfrom sse_starlette.sse import EventSourceResponsefrom huggingface_hub import InferenceClientfrom huggingface_hub.errors import HfHubHTTPError# ---------------------------------------------------------------------------# Config# ---------------------------------------------------------------------------MODEL_ID = os.environ.get("MODEL_ID", "Qwen/Qwen2.5-7B-Instruct")HF_TOKEN = os.environ.get("HF_TOKEN", "")MAX_NEW_TOKENS = int(os.environ.get("MAX_NEW_TOKENS", "500"))API_KEY = os.environ.get("YAPPY_API_KEY", "")MAX_HISTORY_MESSAGES = int(os.environ.get("MAX_HISTORY_MESSAGES", "16"))client = InferenceClient(model=MODEL_ID, token=HF_TOKEN or None)# ---------------------------------------------------------------------------# Mode system prompts3 unmodified lines"You are Yappy, an AI companion created by Rik. You are not a generic ""assistant - you have a distinct personality that adapts to the mode ""the user picked, but you always remember you are Yappy. Keep replies ""conversational and reasonably brief (a few sentences), like texting ""a person, not a long essay. Never use markdown headers or ""bullet-point lists unless the user explicitly asks for one.\n\n""Before every reply, think first. Put your private reasoning inside ""<thinking>...</thinking> tags - 1-3 short sentences on what the user ""needs and what angle/tone fits. Immediately after the closing ""</thinking> tag, write your real reply to the user as plain text, ""with no other tags. Always include both parts.")MODE_PROMPTS = {91 unmodified lines# App# ---------------------------------------------------------------------------app = FastAPI(title="Yappy API", version="3.0.0")app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],2 unmodified linesdef check_auth(request: Request):if not API_KEY:returnsent = request.headers.get("x-api-key", "")if sent != API_KEY:raise HTTPException(status_code=401, detail="Invalid or missing API key")1 unmodified line@app.get("/")def root():return {"status": "ok", "service": "Yappy", "model": MODEL_ID, "mode": "hf-inference-api"}@app.get("/health")10 unmodified linesclass ThinkingSplitter:def __init__(self):self.buffer = ""self.in_thinking = Falseself.seen_thinking_open = Falseself.full_raw = ""self.answer_only = ""def _maybe_partial_tag_tail(self, text: str) -> str:max_tag_len = max(len(THINK_OPEN), len(THINK_CLOSE))79 unmodified linesdef _generate_stream(mode: str, history: List[HistoryTurn], user_message: str, profile: Dict):messages = _build_messages(mode, history, user_message, profile)splitter = ThinkingSplitter()try:stream = client.chat_completion(messages=messages,max_tokens=MAX_NEW_TOKENS,temperature=0.85,stream=True,)for chunk in stream:delta = chunk.choices[0].deltatoken = delta.content if delta and delta.content else ""if token:for event in splitter.feed(token):yield eventfor event in splitter.flush():yield eventexcept HfHubHTTPError as e:status = getattr(e.response, "status_code", None) if hasattr(e, "response") else Noneerror_text = str(e).lower()if status == 503 or "loading" in error_text:yield {"event": "token", "data": "Give me a few seconds to wake up properly and try that again."}else:yield {"event": "token", "data": "I had a hiccup processing that. Try sending it again."}except Exception:yield {"event": "token", "data": "Something went sideways on my end. Try sending that again."}yield {"event": "done", "data": ""}24 unmodified lines@app.post("/chat")def chat_once(payload: ChatRequest, request: Request):check_auth(request)if not payload.message or not payload.message.strip():
app.py+41-101