Spaces:
Sleeping
Sleeping
Adarsh Kumar commited on
Update server.py
Browse files7 unmodified lines891011121314151617184 unmodified lines2324252627284 unmodified lines333435363738391 unmodified line4142434445464748495051525354555657585960616263644 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091106 unmodified lines1171181191201211221236 unmodified lines1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202211 unmodified line2232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253262 unmodified lines3293303313323333343353363373383393403412 unmodified lines3443453463473483493506 unmodified lines3573583593603613623633643653663673683693703715 unmodified lines3773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604611 unmodified line4634644654664674684694704714724734744754764774784794804814824834844854864877 unmodified lines4954964974984995005015025036 unmodified lines51051151251351451551651751814 unmodified lines5335345355365375385395405415425 unmodified lines5485495505515525535542 unmodified lines55755855956056156256310 unmodified lines5745755765775785795805815825835845855865875885895905915925935945953 unmodified lines5996006016026036046056061 unmodified line6086096106116126136146156166176186196206213 unmodified lines6256266276286296306316326336347 unmodified lines║ GET /health ║║ GET / ║║ ║║ Architecture: ║║ • ProviderPool — N pre-warmed WS connections ║║ • acquire() — queue-based fair checkout, auto-heal ║║ • HealthMonitor — periodic background probe + heal ║║ • SSE streaming — thread→asyncio bridge via Queue ║╚═══════════════════════════════════════════════════════════════╝"""4 unmodified linesimport sysimport threadingimport timeimport uuidfrom contextlib import asynccontextmanagerfrom typing import AsyncGenerator, List, Optional4 unmodified linesfrom fastapi.responses import JSONResponse, StreamingResponsefrom pydantic import BaseModel, Field# ─── Import provider ────────────────────────────────────────sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from cloudflare_provider import CloudflareProvider1 unmodified line# LOGGING# ═══════════════════════════════════════════════════════════logging.basicConfig(level=logging.INFO,format="%(asctime)s %(levelname)-8s %(message)s",stream=sys.stdout,datefmt="%H:%M:%S",)log = logging.getLogger("cf-api")# ═══════════════════════════════════════════════════════════# CONFIG (all tunable via environment variables)# ═══════════════════════════════════════════════════════════POOL_SIZE = int(os.getenv("POOL_SIZE", "2"))PORT = int(os.getenv("PORT", "7860"))HOST = os.getenv("HOST", "0.0.0.0")HEALTH_INTERVAL = int(os.getenv("HEALTH_INTERVAL", "60")) # secondsACQUIRE_TIMEOUT = int(os.getenv("ACQUIRE_TIMEOUT", "60")) # wait for free slotSTREAM_TIMEOUT = int(os.getenv("STREAM_TIMEOUT", "120")) # total stream timeoutDEFAULT_MODEL = os.getenv("DEFAULT_MODEL", "@cf/moonshotai/kimi-k2.5")DEFAULT_SYSTEM = os.getenv("DEFAULT_SYSTEM", "You are a helpful assistant.")# ═══════════════════════════════════════════════════════════4 unmodified linescontent: strclass ChatRequest(BaseModel):model: str = DEFAULT_MODELmessages: List[Message]temperature: float = Field(default=1.0, ge=0.0, le=2.0)max_tokens: Optional[int] = Nonestream: bool = Truesystem: Optional[str] = None # extra system-prompt overrideclass CompletionChoice(BaseModel):index: intmessage: dictfinish_reason: strclass CompletionResponse(BaseModel):id: strobject: strcreated: intmodel: strchoices: List[CompletionChoice]usage: dict# ═══════════════════════════════════════════════════════════# MANAGED PROVIDER (pool slot)# ═══════════════════════════════════════════════════════════class ManagedProvider:"""A single pool slot wrapping one CloudflareProvider instance."""def __init__(self, slot_id: int):self.slot_id = slot_idself.provider: Optional[CloudflareProvider] = Noneself.busy = Falseself.born_at = 0.0self.error_count = 0self.request_count = 0# ── Health ──────────────────────────────────────def is_healthy(self) -> bool:if self.provider is None:return False6 unmodified linesexcept Exception:return False# ── Teardown ────────────────────────────────────def close(self):p = self.providerself.provider = None6 unmodified linesdef __repr__(self):state = "busy" if self.busy else ("ok" if self.is_healthy() else "dead")mode = self.provider._mode if self.provider else "none"return (f"<Slot#{self.slot_id} {state} mode={mode!r} "f"reqs={self.request_count} errs={self.error_count}>")# ═══════════════════════════════════════════════════════════# PROVIDER POOL# ═══════════════════════════════════════════════════════════class ProviderPool:"""Pre-warmed pool of CloudflareProvider connections.• initialize() — create all slots at startup• acquire() — async context manager; blocks until a free slot• health_monitor — background coroutine; heals broken idle slots• shutdown() — clean teardown"""def __init__(self, size: int = 2):self.size = sizeself._slots: List[ManagedProvider] = []self._queue: asyncio.Queue = None # set in initialize()self._loop: asyncio.AbstractEventLoop = Noneself._lock = asyncio.Lock()# ─── Startup ──────────────────────────────────async def initialize(self):self._loop = asyncio.get_event_loop()self._queue = asyncio.Queue(maxsize=self.size)log.info(f"🚀 Initializing provider pool (slots={self.size})")results = await asyncio.gather(*[self._spawn_slot(i) for i in range(self.size)],return_exceptions=True,)ok = sum(1 for r in results if not isinstance(r, Exception))log.info(f" Pool ready — {ok}/{self.size} slots healthy")if ok == 0:raise RuntimeError("No provider slots could connect. Check network / Xvfb setup.")async def _spawn_slot(self, slot_id: int) -> ManagedProvider:managed = ManagedProvider(slot_id)def _create() -> CloudflareProvider:log.info(f" [S{slot_id}] Connecting...")return CloudflareProvider(model = DEFAULT_MODEL,system = DEFAULT_SYSTEM,debug = False,use_cache = True,)managed.provider = await asyncio.wait_for(self._loop.run_in_executor(None, _create),timeout=180,)managed.born_at = time.time()self._slots.append(managed)await self._queue.put(managed)mode = managed.provider._modelog.info(f" [S{slot_id}] ✓ Ready mode={mode!r}")return managed# ─── Acquire ──────────────────────────────────@asynccontextmanagerasync def acquire(self):"""Checkout a provider, yield it, return on exit (healing if needed)."""managed: ManagedProvider = await asyncio.wait_for(self._queue.get(),timeout=ACQUIRE_TIMEOUT,)managed.busy = Trueok = Truetry:# Heal before handing outif not managed.is_healthy():log.warning(f"[S{managed.slot_id}] Unhealthy — healing before use")await self._heal(managed)managed.request_count += 11 unmodified lineexcept Exception:managed.error_count += 1ok = Falseraisefinally:managed.busy = False# After use: return if healthy, else heal in backgroundif managed.is_healthy():await self._queue.put(managed)else:log.warning(f"[S{managed.slot_id}] Unhealthy after use — background heal")asyncio.create_task(self._heal_then_return(managed))# ─── Healing ──────────────────────────────────async def _heal(self, managed: ManagedProvider):sid = managed.slot_iddef _recreate() -> CloudflareProvider:managed.close()return CloudflareProvider(model = DEFAULT_MODEL,system = DEFAULT_SYSTEM,debug = False,use_cache = True,)managed.provider = await asyncio.wait_for(self._loop.run_in_executor(None, _recreate),timeout=180,)managed.born_at = time.time()managed.error_count = 0log.info(f"[S{sid}] ✓ Healed mode={managed.provider._mode!r}")async def _heal_then_return(self, managed: ManagedProvider):try:await self._heal(managed)except Exception as e:log.error(f"[S{managed.slot_id}] Heal failed: {e}")# Try a brand-new slot as last resorttry:managed.close()managed.provider = await asyncio.wait_for(self._loop.run_in_executor(None,lambda: CloudflareProvider(model=DEFAULT_MODEL, system=DEFAULT_SYSTEM,debug=False, use_cache=True,),),timeout=180,)managed.born_at = time.time()managed.error_count = 0log.info(f"[S{managed.slot_id}] ✓ Cold-boot recovery succeeded")except Exception as e2:log.error(f"[S{managed.slot_id}] Cold-boot also failed: {e2}")await self._queue.put(managed)# ─── Health monitor ───────────────────────────async def health_monitor(self):"""Periodic background coroutine — checks and heals idle slots."""while True:await asyncio.sleep(HEALTH_INTERVAL)healthy = sum(1 for m in self._slots if m.is_healthy())busy = sum(1 for m in self._slots if m.busy)log.info(f"♥ Health check — {healthy}/{self.size} healthy, "f"{busy} busy, queue={self._queue.qsize()}")for managed in list(self._slots):if not managed.busy and not managed.is_healthy():log.warning(f"[S{managed.slot_id}] Idle but unhealthy — healing")# Pull from queue if it's still there, otherwise skipasyncio.create_task(self._heal_then_return(managed))# ─── Status ───────────────────────────────────@propertydef status(self) -> dict:return {"pool_size": self.size,"queue_free": self._queue.qsize() if self._queue else 0,"slots": [{"id": m.slot_id,"healthy": m.is_healthy(),"busy": m.busy,"mode": m.provider._mode if m.provider else "none","errors": m.error_count,"requests": m.request_count,"age_s": round(time.time() - m.born_at, 1) if m.born_at else 0,}for m in self._slots],}# ─── Shutdown ─────────────────────────────────async def shutdown(self):log.info("Shutting down provider pool...")for m in self._slots:2 unmodified lines# ═══════════════════════════════════════════════════════════# GLOBAL POOL REFERENCE# ═══════════════════════════════════════════════════════════pool: ProviderPool = None# ═══════════════════════════════════════════════════════════# LIFESPAN (startup / shutdown)# ═══════════════════════════════════════════════════════════@asynccontextmanagerasync def lifespan(app: FastAPI):2 unmodified linesawait pool.initialize()monitor = asyncio.create_task(pool.health_monitor())log.info(f"✅ Server ready on {HOST}:{PORT}")yield6 unmodified lines# ═══════════════════════════════════════════════════════════# FASTAPI APP# ═══════════════════════════════════════════════════════════app = FastAPI(title = "Cloudflare AI API",description = "OpenAI-compatible streaming API via Cloudflare AI Playground",version = "1.0.0",lifespan = lifespan,docs_url = "/docs",redoc_url = "/redoc",)app.add_middleware(5 unmodified lines# ═══════════════════════════════════════════════════════════# SSE STREAMING HELPERS# ═══════════════════════════════════════════════════════════def _sse_chunk(content: str, model: str, chunk_id: str) -> str:"""Format one SSE data line in OpenAI chunk format."""payload = {"id": chunk_id,"object": "chat.completion.chunk","created": int(time.time()),"model": model,"choices": [{"index": 0,"delta": {"content": content},"finish_reason": None,}],}return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"def _sse_done(model: str, chunk_id: str) -> str:"""Final SSE chunk with finish_reason=stop."""payload = {"id": chunk_id,"object": "chat.completion.chunk","created": int(time.time()),"model": model,"choices": [{"index": 0,"delta": {},"finish_reason": "stop",}],}return f"data: {json.dumps(payload)}\n\ndata: [DONE]\n\n"def _sse_error(msg: str) -> str:return f"data: {{\"error\": {json.dumps(msg)}}}\n\ndata: [DONE]\n\n"async def _stream_generator(provider: CloudflareProvider,req: ChatRequest,) -> AsyncGenerator[str, None]:"""Bridge between the synchronous provider.chat() generator andFastAPI's async StreamingResponse.Strategy:1. Spin up a background thread that runs provider.chat() andpushes each chunk into an asyncio.Queue.2. Yield SSE-formatted chunks from the queue in the async loop."""loop = asyncio.get_event_loop()q: asyncio.Queue = asyncio.Queue(maxsize=256)chunk_id = f"chatcmpl-{uuid.uuid4().hex[:20]}"cancel = threading.Event()# Build kwargs for providermessages = [{"role": m.role, "content": m.content} for m in req.messages]kwargs: dict = {"messages": messages,"temperature": req.temperature,}if req.model:kwargs["model"] = req.modelif req.max_tokens:kwargs["max_tokens"] = req.max_tokensif req.system:kwargs["system"] = req.system# ── Worker thread ────────────────────────────def _worker():try:for chunk in provider.chat(**kwargs):if cancel.is_set():breakfut = asyncio.run_coroutine_threadsafe(q.put(chunk), loop)fut.result(timeout=10) # backpressure: block thread if queue fullexcept Exception as exc:err = RuntimeError(f"Stream error: {exc}")asyncio.run_coroutine_threadsafe(q.put(err), loop).result(timeout=5)finally:asyncio.run_coroutine_threadsafe(q.put(None), loop).result(timeout=5)1 unmodified linet = threading.Thread(target=_worker, daemon=True)t.start()# ── Async consumer ────────────────────────────try:while True:item = await asyncio.wait_for(q.get(), timeout=STREAM_TIMEOUT)if item is None: # sentinel — stream doneyield _sse_done(req.model, chunk_id)breakif isinstance(item, Exception): # error from workeryield _sse_error(str(item))breakif item: # normal text chunkyield _sse_chunk(item, req.model, chunk_id)except asyncio.TimeoutError:cancel.set()yield _sse_error("Stream timed out — no data received")finally:cancel.set()7 unmodified lines@app.get("/", tags=["Info"])async def root():return {"service": "Cloudflare AI API","version": "1.0.0","status": "running","endpoints": {"chat": "POST /v1/chat/completions","models": "GET /v1/models",6 unmodified lines@app.get("/health", tags=["Info"])async def health():if pool is None:raise HTTPException(503, detail="Pool not yet initialized")healthy = sum(1 for m in pool._slots if m.is_healthy())status = "ok" if healthy > 0 else "degraded"return JSONResponse(content={"status": status, "pool": pool.status},status_code=200 if status == "ok" else 206,14 unmodified lines"object": "list","data": [{"id": m["name"],"object": "model","created": 0,"owned_by": "cloudflare","context_window": m.get("context", 4096),}for m in models5 unmodified linesasync def chat_completions(req: ChatRequest, request: Request):if pool is None:raise HTTPException(503, detail="Pool not initialized")if not req.messages:raise HTTPException(400, detail="`messages` must not be empty")2 unmodified linesasync def _gen():async with pool.acquire() as provider:async for chunk in _stream_generator(provider, req):# Check if client disconnectedif await request.is_disconnected():breakyield chunk10 unmodified lines# ── Non-streaming ──────────────────────────────────────messages = [{"role": m.role, "content": m.content} for m in req.messages]kwargs: dict = {"messages": messages,"temperature": req.temperature,}if req.model:kwargs["model"] = req.modelif req.max_tokens:kwargs["max_tokens"] = req.max_tokensif req.system:kwargs["system"] = req.systemloop = asyncio.get_event_loop()async with pool.acquire() as provider:full_parts: list[str] = []def _collect():for chunk in provider.chat(**kwargs):full_parts.append(chunk)3 unmodified linestimeout=STREAM_TIMEOUT,)response_text = "".join(full_parts)return {"id": f"chatcmpl-{uuid.uuid4().hex[:20]}","object": "chat.completion",1 unmodified line"model": req.model,"choices": [{"index": 0,"message": {"role": "assistant", "content": response_text},"finish_reason": "stop",}],"usage": {"prompt_tokens": 0,"completion_tokens": 0,"total_tokens": 0,},}3 unmodified linesif __name__ == "__main__":uvicorn.run("server:app",host = HOST,port = PORT,log_level = "info",workers = 1, # single worker — state is in-processloop = "asyncio",timeout_keep_alive = 30,)7 unmodified lines89101112131415164 unmodified lines212223242526274 unmodified lines3233343536371 unmodified line3940414243444546474849505152535455565758596061626364654 unmodified lines7071727374757677787980818283848586878889909192939495966 unmodified lines1031041051061071086 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322331 unmodified line2352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313322 unmodified lines3353363373383393403413423433443453463472 unmodified lines3503513523533543553566 unmodified lines3633643653663673683693703713723733743753763775 unmodified lines3833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404411 unmodified line4434444454464474484494504514524534544554564574584594604614624634644654667 unmodified lines4744754764774784794804814824836 unmodified lines49049149249349449549649749849950014 unmodified lines5155165175185195205215225235245 unmodified lines5305315325335345352 unmodified lines53853954054154254310 unmodified lines5545555565575585595605615625635645655665675685695705715725733 unmodified lines5775785795805815821 unmodified line5845855865875885895905915925933 unmodified lines5975985996006016026036046056067 unmodified lines║ GET /health ║║ GET / ║║ ║║ Pool startup: up to 3 retries per slot, logs exact errors. ║║ Health monitor: heals dead idle slots every 60s. ║║ SSE: thread→asyncio bridge with backpressure. ║╚═══════════════════════════════════════════════════════════════╝"""4 unmodified linesimport sysimport threadingimport timeimport tracebackimport uuidfrom contextlib import asynccontextmanagerfrom typing import AsyncGenerator, List, Optional4 unmodified linesfrom fastapi.responses import JSONResponse, StreamingResponsefrom pydantic import BaseModel, Fieldsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from cloudflare_provider import CloudflareProvider1 unmodified line# LOGGING# ═══════════════════════════════════════════════════════════logging.basicConfig(level = logging.INFO,format = "%(asctime)s %(levelname)-8s %(message)s",stream = sys.stdout,datefmt = "%H:%M:%S",)log = logging.getLogger("cf-api")# ═══════════════════════════════════════════════════════════# CONFIG# ═══════════════════════════════════════════════════════════POOL_SIZE = int(os.getenv("POOL_SIZE", "2"))PORT = int(os.getenv("PORT", "7860"))HOST = os.getenv("HOST", "0.0.0.0")HEALTH_INTERVAL = int(os.getenv("HEALTH_INTERVAL", "60"))ACQUIRE_TIMEOUT = int(os.getenv("ACQUIRE_TIMEOUT", "90"))STREAM_TIMEOUT = int(os.getenv("STREAM_TIMEOUT", "120"))DEFAULT_MODEL = os.getenv("DEFAULT_MODEL", "@cf/moonshotai/kimi-k2.5")DEFAULT_SYSTEM = os.getenv("DEFAULT_SYSTEM", "You are a helpful assistant.")SLOT_RETRIES = int(os.getenv("SLOT_RETRIES", "3"))SLOT_RETRY_WAIT = int(os.getenv("SLOT_RETRY_WAIT", "10")) # seconds between retries# ═══════════════════════════════════════════════════════════4 unmodified linescontent: strclass ChatRequest(BaseModel):model: str = DEFAULT_MODELmessages: List[Message]temperature: float = Field(default=1.0, ge=0.0, le=2.0)max_tokens: Optional[int] = Nonestream: bool = Truesystem: Optional[str] = None# ═══════════════════════════════════════════════════════════# MANAGED PROVIDER SLOT# ═══════════════════════════════════════════════════════════class ManagedProvider:def __init__(self, slot_id: int):self.slot_id = slot_idself.provider: Optional[CloudflareProvider] = Noneself.busy = Falseself.born_at = 0.0self.error_count = 0self.request_count = 0self.last_error = ""def is_healthy(self) -> bool:if self.provider is None:return False6 unmodified linesexcept Exception:return Falsedef close(self):p = self.providerself.provider = None6 unmodified linesdef __repr__(self):state = "busy" if self.busy else ("ok" if self.is_healthy() else "dead")mode = self.provider._mode if self.provider else "none"return f"<Slot#{self.slot_id} {state} mode={mode!r} reqs={self.request_count}>"# ═══════════════════════════════════════════════════════════# PROVIDER POOL# ═══════════════════════════════════════════════════════════class ProviderPool:def __init__(self, size: int = 2):self.size = sizeself._slots: List[ManagedProvider] = []self._queue: asyncio.Queue = Noneself._loop: asyncio.AbstractEventLoop = None# ─── Startup ──────────────────────────────────────────async def initialize(self):self._loop = asyncio.get_event_loop()self._queue = asyncio.Queue(maxsize=self.size)log.info(f"🚀 Initializing provider pool (slots={self.size})")log.info(f" DISPLAY={os.environ.get('DISPLAY', 'NOT SET')}")log.info(f" XVFB_EXTERNAL={os.environ.get('XVFB_EXTERNAL', '0')}")log.info(f" VR_DISPLAY={os.environ.get('VR_DISPLAY', '0')}")results = await asyncio.gather(*[self._spawn_slot_with_retry(i) for i in range(self.size)],return_exceptions=True,)ok = sum(1 for r in results if not isinstance(r, Exception))fail = sum(1 for r in results if isinstance(r, Exception))if fail:for i, r in enumerate(results):if isinstance(r, Exception):log.error(f" [S{i}] FAILED: {r}")log.info(f" Pool ready — {ok}/{self.size} slots healthy")if ok == 0:raise RuntimeError(f"All {self.size} provider slots failed to connect.\n"f" → Check DISPLAY / XVFB_EXTERNAL environment variables.\n"f" → Ensure entrypoint.sh started Xvfb before the server.\n"f" → Check network connectivity to playground.ai.cloudflare.com.")async def _spawn_slot_with_retry(self, slot_id: int) -> "ManagedProvider":"""Try to create a slot, retrying up to SLOT_RETRIES times."""managed = ManagedProvider(slot_id)for attempt in range(1, SLOT_RETRIES + 1):try:log.info(f" [S{slot_id}] Connecting... (attempt {attempt}/{SLOT_RETRIES})")def _create():return CloudflareProvider(model = DEFAULT_MODEL,system = DEFAULT_SYSTEM,debug = True, # verbose during init so we can see failuresuse_cache = True,)managed.provider = await asyncio.wait_for(self._loop.run_in_executor(None, _create),timeout=180,)managed.provider.debug = False # quiet after successful bootmanaged.born_at = time.time()self._slots.append(managed)await self._queue.put(managed)mode = managed.provider._modelog.info(f" [S{slot_id}] ✓ Ready mode={mode!r}")return managedexcept asyncio.TimeoutError:err = f"Slot {slot_id} timed out (attempt {attempt})"log.warning(f" [S{slot_id}] ⚠ {err}")managed.last_error = errmanaged.close()except Exception as exc:err = str(exc)# Print full traceback for debugginglog.warning(f" [S{slot_id}] ⚠ Attempt {attempt} failed:\n"+ traceback.format_exc())managed.last_error = errmanaged.close()if attempt < SLOT_RETRIES:log.info(f" [S{slot_id}] Retrying in {SLOT_RETRY_WAIT}s...")await asyncio.sleep(SLOT_RETRY_WAIT)raise RuntimeError(f"Slot {slot_id} failed after {SLOT_RETRIES} attempts. "f"Last error: {managed.last_error}")# ─── Acquire ──────────────────────────────────────────@asynccontextmanagerasync def acquire(self):managed: ManagedProvider = await asyncio.wait_for(self._queue.get(),timeout=ACQUIRE_TIMEOUT,)managed.busy = Truetry:if not managed.is_healthy():log.warning(f"[S{managed.slot_id}] Unhealthy at checkout — healing now")await self._heal(managed)managed.request_count += 11 unmodified lineexcept Exception:managed.error_count += 1raisefinally:managed.busy = Falseif managed.is_healthy():await self._queue.put(managed)else:log.warning(f"[S{managed.slot_id}] Dead after use — background heal")asyncio.create_task(self._heal_then_return(managed))# ─── Healing ──────────────────────────────────────────async def _heal(self, managed: ManagedProvider):sid = managed.slot_idlog.info(f"[S{sid}] Healing slot...")def _recreate():managed.close()return CloudflareProvider(model = DEFAULT_MODEL,system = DEFAULT_SYSTEM,debug = True,use_cache = True,)try:managed.provider = await asyncio.wait_for(self._loop.run_in_executor(None, _recreate),timeout=180,)managed.provider.debug = Falsemanaged.born_at = time.time()managed.error_count = 0managed.last_error = ""log.info(f"[S{sid}] ✓ Healed mode={managed.provider._mode!r}")except Exception as e:managed.last_error = str(e)log.error(f"[S{sid}] ✗ Heal failed: {e}\n{traceback.format_exc()}")raiseasync def _heal_then_return(self, managed: ManagedProvider):sid = managed.slot_idfor attempt in range(1, SLOT_RETRIES + 1):try:await self._heal(managed)await self._queue.put(managed)returnexcept Exception as e:log.warning(f"[S{sid}] Heal attempt {attempt}/{SLOT_RETRIES} failed: {e}")if attempt < SLOT_RETRIES:await asyncio.sleep(SLOT_RETRY_WAIT)# Last resort: put it back anyway so queue doesn't shrink permanentlylog.error(f"[S{sid}] All heal attempts failed — slot may be non-functional")await self._queue.put(managed)# ─── Health monitor ───────────────────────────────────async def health_monitor(self):while True:await asyncio.sleep(HEALTH_INTERVAL)healthy = sum(1 for m in self._slots if m.is_healthy())busy = sum(1 for m in self._slots if m.busy)log.info(f"♥ Pool — {healthy}/{self.size} healthy "f"{busy} busy queue={self._queue.qsize()}")for managed in list(self._slots):if not managed.busy and not managed.is_healthy():log.warning(f"[S{managed.slot_id}] Idle+dead — healing in background")asyncio.create_task(self._heal_then_return(managed))# ─── Status ───────────────────────────────────────────@propertydef status(self) -> dict:return {"pool_size": self.size,"queue_free": self._queue.qsize() if self._queue else 0,"slots": [{"id": m.slot_id,"healthy": m.is_healthy(),"busy": m.busy,"mode": m.provider._mode if m.provider else "none","errors": m.error_count,"requests": m.request_count,"age_s": round(time.time() - m.born_at, 1) if m.born_at else 0,"last_error": m.last_error or None,}for m in self._slots],}# ─── Shutdown ─────────────────────────────────────────async def shutdown(self):log.info("Shutting down provider pool...")for m in self._slots:2 unmodified lines# ═══════════════════════════════════════════════════════════# GLOBAL POOL# ═══════════════════════════════════════════════════════════pool: ProviderPool = None# ═══════════════════════════════════════════════════════════# LIFESPAN# ═══════════════════════════════════════════════════════════@asynccontextmanagerasync def lifespan(app: FastAPI):2 unmodified linesawait pool.initialize()monitor = asyncio.create_task(pool.health_monitor())log.info(f"✅ Server ready {HOST}:{PORT}")yield6 unmodified lines# ═══════════════════════════════════════════════════════════# APP# ═══════════════════════════════════════════════════════════app = FastAPI(title = "Cloudflare AI API",description = "OpenAI-compatible API via Cloudflare AI Playground",version = "1.1.0",lifespan = lifespan,docs_url = "/docs",redoc_url = "/redoc",)app.add_middleware(5 unmodified lines# ═══════════════════════════════════════════════════════════# SSE HELPERS# ═══════════════════════════════════════════════════════════def _sse_chunk(content: str, model: str, cid: str) -> str:return "data: " + json.dumps({"id": cid,"object": "chat.completion.chunk","created": int(time.time()),"model": model,"choices": [{"index": 0, "delta": {"content": content}, "finish_reason": None}],}, ensure_ascii=False) + "\n\n"def _sse_done(model: str, cid: str) -> str:return "data: " + json.dumps({"id": cid,"object": "chat.completion.chunk","created": int(time.time()),"model": model,"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],}) + "\n\ndata: [DONE]\n\n"def _sse_error(msg: str) -> str:return f'data: {{"error": {json.dumps(msg)}}}\n\ndata: [DONE]\n\n'async def _stream_generator(provider: CloudflareProvider,req: ChatRequest,) -> AsyncGenerator[str, None]:loop = asyncio.get_event_loop()q: asyncio.Queue = asyncio.Queue(maxsize=512)cid = f"chatcmpl-{uuid.uuid4().hex[:20]}"cancel = threading.Event()messages = [{"role": m.role, "content": m.content} for m in req.messages]kwargs = {"messages": messages,"temperature": req.temperature,"model": req.model,}if req.max_tokens:kwargs["max_tokens"] = req.max_tokensif req.system:kwargs["system"] = req.systemdef _worker():try:for chunk in provider.chat(**kwargs):if cancel.is_set():breakfut = asyncio.run_coroutine_threadsafe(q.put(chunk), loop)fut.result(timeout=10)except Exception as exc:err = RuntimeError(str(exc))asyncio.run_coroutine_threadsafe(q.put(err), loop).result(timeout=5)finally:asyncio.run_coroutine_threadsafe(q.put(None), loop).result(timeout=5)1 unmodified linet = threading.Thread(target=_worker, daemon=True)t.start()try:while True:item = await asyncio.wait_for(q.get(), timeout=STREAM_TIMEOUT)if item is None:yield _sse_done(req.model, cid)breakif isinstance(item, Exception):yield _sse_error(str(item))breakif item:yield _sse_chunk(item, req.model, cid)except asyncio.TimeoutError:cancel.set()yield _sse_error("Stream timed out")finally:cancel.set()7 unmodified lines@app.get("/", tags=["Info"])async def root():return {"service": "Cloudflare AI API","version": "1.1.0","status": "running","display": os.environ.get("DISPLAY", "not set"),"endpoints": {"chat": "POST /v1/chat/completions","models": "GET /v1/models",6 unmodified lines@app.get("/health", tags=["Info"])async def health():if pool is None:raise HTTPException(503, detail="Pool not initialized")healthy = sum(1 for m in pool._slots if m.is_healthy())status = "ok" if healthy > 0 else "degraded"return JSONResponse(content={"status": status, "pool": pool.status},status_code=200 if status == "ok" else 206,14 unmodified lines"object": "list","data": [{"id": m["name"],"object": "model","created": 0,"owned_by": "cloudflare","context_window": m.get("context", 4096),}for m in models5 unmodified linesasync def chat_completions(req: ChatRequest, request: Request):if pool is None:raise HTTPException(503, detail="Pool not initialized")if not req.messages:raise HTTPException(400, detail="`messages` must not be empty")2 unmodified linesasync def _gen():async with pool.acquire() as provider:async for chunk in _stream_generator(provider, req):if await request.is_disconnected():breakyield chunk10 unmodified lines# ── Non-streaming ──────────────────────────────────────messages = [{"role": m.role, "content": m.content} for m in req.messages]kwargs = {"messages": messages,"temperature": req.temperature,"model": req.model,}if req.max_tokens:kwargs["max_tokens"] = req.max_tokensif req.system:kwargs["system"] = req.systemloop = asyncio.get_event_loop()full_parts: list[str] = []async with pool.acquire() as provider:def _collect():for chunk in provider.chat(**kwargs):full_parts.append(chunk)3 unmodified linestimeout=STREAM_TIMEOUT,)return {"id": f"chatcmpl-{uuid.uuid4().hex[:20]}","object": "chat.completion",1 unmodified line"model": req.model,"choices": [{"index": 0,"message": {"role": "assistant", "content": "".join(full_parts)},"finish_reason": "stop",}],"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},}3 unmodified linesif __name__ == "__main__":uvicorn.run("server:app",host = HOST,port = PORT,log_level = "info",workers = 1,loop = "asyncio",timeout_keep_alive = 30,)
server.py+207-235