"""FastAPI application for Web3Coders. Serves the single-page chat UI and a streaming chat endpoint that proxies to the LLM service defined in ``llm_service``. All model interaction and fallback behaviour lives in that module; this file is HTTP-only. Run locally: uvicorn app:app --reload --port 8000 """ from __future__ import annotations import json from pathlib import Path from typing import Annotated, AsyncIterator from fastapi import FastAPI, HTTPException, Request, status from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.errors import RateLimitExceeded from slowapi.util import get_remote_address from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.responses import Response from llm_service import MODEL_ID, WEB3_CODER_SYSTEM_PROMPT, stream_chat # --------------------------------------------------------------------------- # # Constants # --------------------------------------------------------------------------- # BASE_DIR = Path(__file__).parent MAX_MESSAGE_LENGTH = 8_000 MAX_HISTORY_LENGTH = 20 MAX_REQUEST_BYTES = 1024 * 1024 # 1 MiB CHAT_RATE_LIMIT = "30/minute" # SSE framing — must match what the browser client expects. SSE_DELTA_PREFIX = "data: " SSE_DONE_FRAME = "data: [DONE]\n\n" SSE_HEADERS = { "Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no", # disable proxy buffering (nginx et al.) "Connection": "keep-alive", } # --------------------------------------------------------------------------- # # Models # --------------------------------------------------------------------------- # class Message(BaseModel): """One chat message, either from the user or the assistant.""" role: Annotated[str, Field(pattern="^(user|assistant)$")] content: Annotated[str, Field(min_length=1, max_length=MAX_MESSAGE_LENGTH)] class ChatRequest(BaseModel): """A chat request containing a bounded conversation history.""" messages: Annotated[ list[Message], Field(min_length=1, max_length=MAX_HISTORY_LENGTH), ] # --------------------------------------------------------------------------- # # Middleware # --------------------------------------------------------------------------- # class RequestSizeLimitMiddleware(BaseHTTPMiddleware): """Reject oversized request bodies before FastAPI parses them.""" def __init__(self, app, max_bytes: int, guarded_paths: set[str]) -> None: super().__init__(app) self.max_bytes = max_bytes self.guarded_paths = guarded_paths async def dispatch( self, request: Request, call_next: RequestResponseEndpoint, ) -> Response: if request.method == "POST" and request.url.path in self.guarded_paths: raw_len = request.headers.get("content-length") if raw_len is not None: try: length = int(raw_len) except ValueError: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid Content-Length header", ) if length > self.max_bytes: raise HTTPException( status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail="Request too large", ) return await call_next(request) # --------------------------------------------------------------------------- # # App # --------------------------------------------------------------------------- # app = FastAPI(title="Web3Coders", version="1.0.0") limiter = Limiter(key_func=get_remote_address) app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) app.add_middleware( RequestSizeLimitMiddleware, max_bytes=MAX_REQUEST_BYTES, guarded_paths={"/api/chat"}, ) # --------------------------------------------------------------------------- # # SSE helpers # --------------------------------------------------------------------------- # def _sse(payload: dict) -> str: """Encode a JSON object as a single SSE frame.""" return f"{SSE_DELTA_PREFIX}{json.dumps(payload, ensure_ascii=False)}\n\n" async def _event_stream(messages: list[dict]) -> AsyncIterator[str]: """Adapt the LLM service's plain-text stream to SSE frames.""" try: async for delta in stream_chat(messages, WEB3_CODER_SYSTEM_PROMPT): if delta: yield _sse({"delta": delta}) except Exception as exc: # pragma: no cover — defensive only # The service already swallows expected transport errors; this # catches anything truly unexpected so the client sees a frame # instead of a dangling connection. yield _sse({"error": str(exc)}) finally: yield SSE_DONE_FRAME # --------------------------------------------------------------------------- # # Routes # --------------------------------------------------------------------------- # @app.post("/api/chat") @limiter.limit(CHAT_RATE_LIMIT) async def chat(request: Request, req: ChatRequest) -> StreamingResponse: """Stream an assistant reply as Server-Sent Events.""" history = [{"role": m.role, "content": m.content} for m in req.messages] return StreamingResponse( _event_stream(history), media_type="text/event-stream", headers=SSE_HEADERS, ) @app.get("/api/health") async def health() -> dict[str, str]: """Liveness probe plus the active model id for debugging.""" return {"status": "ok", "model": MODEL_ID} @app.get("/", response_class=HTMLResponse) async def index() -> FileResponse: return FileResponse(BASE_DIR / "index.html") @app.get("/style.css") async def style() -> FileResponse: return FileResponse(BASE_DIR / "style.css", media_type="text/css") @app.get("/index.js") async def js() -> FileResponse: return FileResponse(BASE_DIR / "index.js", media_type="application/javascript") app.mount("/static", StaticFiles(directory=BASE_DIR), name="static")