Spaces:
Paused
Paused
THOX ZeroGPU model Space
Browse filesFiles changed (2)
- app.py+29-8
- thox_auth.py+38
380 unmodified lines38138238338438538638738838939039139239341 unmodified lines43543643743843944044144244344444544644744844949 unmodified lines49950050150250350450550698 unmodified lines605606607608609610380 unmodified linesname: str | None = Noneclass ChatRequest(BaseModel):model: str | None = Nonemessages: list[ChatMessage]stream: bool = Falsemax_tokens: int | None = Field(default=None, ge=1, le=4096)temperature: float = Field(default=0.7, ge=0.0, le=2.0)top_p: float = Field(default=0.95, gt=0.0, le=1.0)# Without these two fields Pydantic silently DROPS what the client sent, so the# model is never told a tool exists and every call looks like "I have no tools".tools: Any = None41 unmodified linesmessages = _normalise_messages([m.model_dump() for m in req.messages])# tool_choice "none" means the caller explicitly wants no tool use this turn.tools = None if (req.tool_choice == "none") else (req.tools or None)max_new = req.max_tokens or 512completion_id = f"chatcmpl-{uuid.uuid4().hex[:24]}"created = int(time.time())if not req.stream:parts: list[str] = []finish = "stop"for kind, payload in _stream_tokens(messages, max_new, req.temperature,req.top_p, tools):if kind == "delta":parts.append(payload)else:49 unmodified lines# typing effect only on tool-enabled turns; ordinary chat still streams.buffered: list[str] = []try:for kind, payload in _stream_tokens(messages, max_new, req.temperature,req.top_p, tools):if kind == "finish":finish = payloadcontinue98 unmodified linesdemo.app.router.routes.insert(0, route)grafted.append(path)print(f"[thox] grafted OpenAI routes onto gradio app: {grafted}", flush=True)# launch(prevent_thread_lock=True) returns immediately; block so PID 1 stays alive.demo.block_thread()380 unmodified lines38138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141 unmodified lines45345445545645745845946046146246346446546646746846949 unmodified lines51952052152252352452552698 unmodified lines625626627628629630631380 unmodified linesname: str | None = None# Ceilings are enforced by CLAMPING, not by Pydantic bounds.## `Field(le=4096)` looks tidier but is an OpenAI incompatibility: FastAPI turns a# violation into `422 {"detail": [...]}`, while the OpenAI API returns# `400 {"error": {...}}`. Measured with the real `openai` SDK, `max_tokens=100000` raised# `UnprocessableEntityError` on all three template Spaces -- a client that reads# `error.message` sees nothing at all. Out-of-range sampling values are the caller being# sloppy, not the caller being wrong, so clamp them and answer.MAX_OUTPUT_TOKENS = 4096def _clamp(value, low, high, fallback):try:return min(max(type(low)(value), low), high)except (TypeError, ValueError):return fallbackclass ChatRequest(BaseModel):model: str | None = Nonemessages: list[ChatMessage]stream: bool = Falsemax_tokens: int | None = Nonetemperature: float = 0.7top_p: float = 0.95# Without these two fields Pydantic silently DROPS what the client sent, so the# model is never told a tool exists and every call looks like "I have no tools".tools: Any = None41 unmodified linesmessages = _normalise_messages([m.model_dump() for m in req.messages])# tool_choice "none" means the caller explicitly wants no tool use this turn.tools = None if (req.tool_choice == "none") else (req.tools or None)max_new = _clamp(req.max_tokens or 512, 1, MAX_OUTPUT_TOKENS, 512)temperature = _clamp(req.temperature, 0.0, 2.0, 0.7)top_p = _clamp(req.top_p, 0.001, 1.0, 0.95)completion_id = f"chatcmpl-{uuid.uuid4().hex[:24]}"created = int(time.time())if not req.stream:parts: list[str] = []finish = "stop"for kind, payload in _stream_tokens(messages, max_new, temperature,top_p, tools):if kind == "delta":parts.append(payload)else:49 unmodified lines# typing effect only on tool-enabled turns; ordinary chat still streams.buffered: list[str] = []try:for kind, payload in _stream_tokens(messages, max_new, temperature,top_p, tools):if kind == "finish":finish = payloadcontinue98 unmodified linesdemo.app.router.routes.insert(0, route)grafted.append(path)print(f"[thox] grafted OpenAI routes onto gradio app: {grafted}", flush=True)thox_auth.install(demo.app)# launch(prevent_thread_lock=True) returns immediately; block so PID 1 stays alive.demo.block_thread()
81 unmodified lines82838481 unmodified linesif not hmac.compare_digest(presented, expected):return _deny("Incorrect API key provided.", "invalid_api_key")return None81 unmodified lines82838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112281 unmodified linesif not hmac.compare_digest(presented, expected):return _deny("Incorrect API key provided.", "invalid_api_key")return None# --------------------------------------------------------------------------------------# OpenAI-shaped validation errors# --------------------------------------------------------------------------------------def openai_validation_handler(request, exc):"""FastAPI answers a bad body with `422 {"detail": [...]}`; OpenAI uses`400 {"error": {...}}`. A client that reads `error.message` sees nothing in theformer, so translate."""try:first = exc.errors()[0]where = ".".join(str(p) for p in first.get("loc", ()) if p != "body")message = f"{first.get('msg', 'Invalid request')}" + (f" (at '{where}')" if where else "")param = where or Noneexcept Exception: # noqa: BLE001message, param = "Invalid request body.", Nonereturn JSONResponse(status_code=400,content={"error": {"message": message, "type": "invalid_request_error","param": param, "code": None}},)def install(app) -> None:"""Attach the handler to the app that will actually serve the request.This has to be Gradio's app, not the FastAPI instance the routes were declared on:Starlette resolves exception handlers against the app whose middleware stack isrunning, and the routes are grafted onto Gradio's router. Clearing`middleware_stack` forces a rebuild so a handler added after `launch()` is picked up-- adding to the dict alone would be silently ignored, because the stack that closedover the old handler map is already built."""from fastapi.exceptions import RequestValidationErrorapp.add_exception_handler(RequestValidationError, openai_validation_handler)app.middleware_stack = Noneprint("[thox] installed OpenAI-shaped validation error handler", flush=True)
app.py+29-8
thox_auth.py+38