Spaces:
Paused
Paused
Update app.py
Browse files17 unmodified lines1819202122232425266 unmodified lines333435363738391 unmodified line4142434445464719 unmodified lines676869707172733 unmodified lines777879808182832 unmodified lines86878889909192937 unmodified lines1011021031041051061079 unmodified lines11711811912012112212329 unmodified lines15315415515615715815916016116216316416516616716816917017117217317 unmodified linesallow_headers=["*"],)OLLAMA_BASE = "http://localhost:11434"MODEL = os.environ.get("DEFAULT_MODEL", "qwen2.5-coder:7b-instruct-q4_K_M")API_TOKEN = os.environ.get("API_TOKEN", "")def verify_token(creds: HTTPAuthorizationCredentials = Depends(security)):6 unmodified lines@app.get("/")async def root():return {"status": "ok", "model": MODEL}@app.get("/health")1 unmodified linetry:r = requests.get(f"{OLLAMA_BASE}/api/tags", timeout=5)models = [m["name"] for m in r.json().get("models", [])]return {"status": "ok", "model": MODEL, "available_models": models}except Exception as e:return {"status": "starting", "error": str(e)}19 unmodified lines"messages": body.get("messages", []),"stream": stream,"options": {"num_ctx": body.get("max_tokens", 32768),"temperature": body.get("temperature", 0.7),}}3 unmodified linestry:with requests.post(f"{OLLAMA_BASE}/v1/chat/completions",json=payload, stream=True, timeout=300) as r:for chunk in r.iter_content(chunk_size=None):if chunk:2 unmodified linesyield f"data: {{\"error\": \"{e}\"}}\n\n".encode()return StreamingResponse(generate(), media_type="text/event-stream")r = requests.post(f"{OLLAMA_BASE}/v1/chat/completions", json=payload, timeout=300)return r.json()@app.post("/v1/messages")7 unmodified lines"messages": body.get("messages", []),"stream": stream,"options": {"num_ctx": body.get("max_tokens", 32768),"temperature": body.get("temperature", 0.7),}}9 unmodified linestry:with requests.post(f"{OLLAMA_BASE}/v1/chat/completions",json=payload, stream=True, timeout=300) as r:buf = ""for chunk in r.iter_content(chunk_size=None):29 unmodified linesreturn StreamingResponse(generate_anthropic(), media_type="text/event-stream")r = requests.post(f"{OLLAMA_BASE}/v1/chat/completions", json=payload, timeout=300)data = r.json()content = (data.get("choices") or [{}])[0].get("message", {}).get("content", "")return {"id": data.get("id", f"msg_{int(time.time())}"),"type": "message","role": "assistant","content": [{"type": "text", "text": content}],"model": model,"stop_reason": "end_turn","usage": {"input_tokens": data.get("usage", {}).get("prompt_tokens", 0),"output_tokens": data.get("usage", {}).get("completion_tokens", 0)}}if __name__ == "__main__":17 unmodified lines181920212223242526272829306 unmodified lines373839404142431 unmodified line4546474849505119 unmodified lines71727374757677783 unmodified lines828384858687882 unmodified lines9192939495969798991001017 unmodified lines1091101111121131141151169 unmodified lines12612712812913013113229 unmodified lines16216316416516616716816917017117217317417517617717817918018118218318418517 unmodified linesallow_headers=["*"],)OLLAMA_BASE = "http://localhost:11434"MODEL = os.environ.get("DEFAULT_MODEL", "qwen2.5-coder:7b-instruct-q4_K_M")API_TOKEN = os.environ.get("API_TOKEN", "")# Free CPU tier: keep context small or requests will timeout after 5 minMAX_CTX = 4096MAX_OUT = 1024TIMEOUT = 240 # 4 min hard limit — under HF's 5 min killdef verify_token(creds: HTTPAuthorizationCredentials = Depends(security)):6 unmodified lines@app.get("/")async def root():return {"status": "ok", "model": MODEL, "max_ctx": MAX_CTX}@app.get("/health")1 unmodified linetry:r = requests.get(f"{OLLAMA_BASE}/api/tags", timeout=5)models = [m["name"] for m in r.json().get("models", [])]return {"status": "ok", "model": MODEL, "available_models": models, "max_ctx": MAX_CTX}except Exception as e:return {"status": "starting", "error": str(e)}19 unmodified lines"messages": body.get("messages", []),"stream": stream,"options": {"num_ctx": MAX_CTX,"num_predict": min(body.get("max_tokens", MAX_OUT), MAX_OUT),"temperature": body.get("temperature", 0.7),}}3 unmodified linestry:with requests.post(f"{OLLAMA_BASE}/v1/chat/completions",json=payload, stream=True, timeout=TIMEOUT) as r:for chunk in r.iter_content(chunk_size=None):if chunk:2 unmodified linesyield f"data: {{\"error\": \"{e}\"}}\n\n".encode()return StreamingResponse(generate(), media_type="text/event-stream")try:r = requests.post(f"{OLLAMA_BASE}/v1/chat/completions", json=payload, timeout=TIMEOUT)return r.json()except requests.Timeout:raise HTTPException(504, "Inference timeout — try a shorter prompt")@app.post("/v1/messages")7 unmodified lines"messages": body.get("messages", []),"stream": stream,"options": {"num_ctx": MAX_CTX,"num_predict": min(body.get("max_tokens", MAX_OUT), MAX_OUT),"temperature": body.get("temperature", 0.7),}}9 unmodified linestry:with requests.post(f"{OLLAMA_BASE}/v1/chat/completions",json=payload, stream=True, timeout=TIMEOUT) as r:buf = ""for chunk in r.iter_content(chunk_size=None):29 unmodified linesreturn StreamingResponse(generate_anthropic(), media_type="text/event-stream")try:r = requests.post(f"{OLLAMA_BASE}/v1/chat/completions", json=payload, timeout=TIMEOUT)data = r.json()content = (data.get("choices") or [{}])[0].get("message", {}).get("content", "")return {"id": data.get("id", f"msg_{int(time.time())}"),"type": "message","role": "assistant","content": [{"type": "text", "text": content}],"model": model,"stop_reason": "end_turn","usage": {"input_tokens": data.get("usage", {}).get("prompt_tokens", 0),"output_tokens": data.get("usage", {}).get("completion_tokens", 0)}}except requests.Timeout:raise HTTPException(504, "Inference timeout — try a shorter prompt")if __name__ == "__main__":
app.py+37-25