"""The LLM servers' addresses on The Kurgan's web server: /strata/... and /llama/... http://127.0.0.1:8080/strata/v1 OpenAI-compatible base URL for Strata http://127.0.0.1:8080/llama/v1 ... for llama.cpp (no API key needed; any key is accepted) http://127.0.0.1:8080/strata/ each server's own chat page (and everything else it serves) http://127.0.0.1:8080/llama/ A request starts its server if it isn't running (see AiService.claim, which also stops the other server once that one is idle) and the reply is streamed back as it is generated. A client that hangs up (a timeout, or the user cancelling) is noticed within a second, even while it is still waiting: its place is given up and the connection to the server closed, which stops the work on it. The log then says how long the client waited and at what stage. GET .../v1/models is answered here while a server is stopped, so a client listing the models of both doesn't make them swap. Security: the web server's Host check applies (DNS rebinding). A request carrying an Origin header other than this server's comes from another site's page and is refused, as is anything else a browser marks cross-site except opening a page. Pages of this server (the chat pages) are let through with the Origin removed, so each server treats them like any local client. llama-server keeps its API key on its own port, and this proxy supplies it, so neither server asks clients here for a key. """ from __future__ import annotations import http.client import json import logging import re import select import socket import time log = logging.getLogger(__name__) ROUTE = re.compile(r"^/(strata|llama)(/[^?#]*)?(\?.*)?$") MAX_BODY = 64 * 1024 * 1024 # images and very long prompts are big, but not this big CONNECT_TIMEOUT = 10.0 READ_TIMEOUT = 1800.0 # between bytes: a model load plus a long prompt can take minutes REQUEST_SKIP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "host", "content-length", "origin", "expect"} RESPONSE_SKIP = {"connection", "keep-alive", "proxy-authenticate", "te", "trailer", "transfer-encoding", "upgrade", "server", "date"} class BodyError(Exception): def __init__(self, message: str, status: int): super().__init__(message) self.status = status def match(path: str) -> tuple[str, str | None] | None: """("llama", "/v1/models?x") for "/llama/v1/models?x"; ("llama", None) for "/llama"; None otherwise.""" m = ROUTE.match(path) if m is None: return None rest = m[2] return m[1], None if rest is None else rest + (m[3] or "") def _error(handler, status: int, message: str) -> None: body = json.dumps({"error": {"message": message, "type": "kurgan"}}).encode() handler.send_response(status) handler.send_header("Content-Type", "application/json") handler.send_header("Content-Length", str(len(body))) handler.send_header("Cache-Control", "no-store") handler.send_header("Connection", "close") handler.end_headers() handler.close_connection = True if handler.command != "HEAD": handler.wfile.write(body) def _read_body(handler) -> bytes | None: """The request body (Content-Length or chunked), None if there is none.""" if handler.headers.get("Transfer-Encoding", "").lower() == "chunked": parts, total = [], 0 while True: line = handler.rfile.readline(1024) try: size = int(line.split(b";")[0].strip(), 16) except ValueError: raise BodyError("malformed chunked body", 400) from None if size == 0: while handler.rfile.readline(1024) not in (b"\r\n", b"\n", b""): # trailers pass return b"".join(parts) total += size if total > MAX_BODY: raise BodyError("request body too large", 413) parts.append(handler.rfile.read(size)) handler.rfile.readline(8) length = handler.headers.get("Content-Length") if length is None: return None try: length = int(length) except ValueError: raise BodyError("bad Content-Length", 400) from None if length < 0: raise BodyError("bad Content-Length", 400) if length > MAX_BODY: remaining = min(length, 1024 * 1024) # read a little so the client sees the answer; beyond that, give up while remaining > 0: chunk = handler.rfile.read(min(remaining, 65536)) if not chunk: break remaining -= len(chunk) raise BodyError("request body too large", 413) return handler.rfile.read(length) def _models(handler, backend, rest: str) -> None: """OpenAI's model list, without starting the server.""" path = rest.split("?", 1)[0].rstrip("/") models = [{"id": m, "object": "model", "created": 0, "owned_by": backend.key} for m in backend.model_ids()] if path == "/v1/models": data = {"object": "list", "data": models} else: wanted = path[len("/v1/models/"):] data = next((m for m in models if m["id"] == wanted), None) if data is None: _error(handler, 404, f"model {wanted!r} not found") return body = json.dumps(data).encode() handler.send_response(200) handler.send_header("Content-Type", "application/json") handler.send_header("Content-Length", str(len(body))) handler.send_header("Connection", "close") handler.end_headers() handler.close_connection = True handler.wfile.write(body) def _location(value: str, backend) -> str: """Map a redirect from the server's own address onto its path here.""" internal = f"http://127.0.0.1:{backend.port}" if value.startswith(internal): value = value[len(internal):] or "/" if not value.startswith("/"): return value if backend.prefix and value.startswith(backend.prefix): value = value[len(backend.prefix):] or "/" return f"/{backend.key}{value}" class ClientGone(Exception): """The client closed its connection (it timed out or was cancelled); args[0] says when.""" def client_gone(handler) -> bool: """True once the client has closed its connection. The request has been read in full by then, so a readable socket with nothing to read means the client hung up.""" sock = handler.connection try: readable, _, _ = select.select([sock], [], [], 0) return bool(readable) and sock.recv(1, socket.MSG_PEEK) == b"" except (OSError, ValueError): return True def handle(handler, ai, hosts: set[str], origins: set[str]) -> None: """Serve one request for /strata/... or /llama/... (handler is a BaseHTTPRequestHandler).""" started = time.monotonic() try: _serve(handler, ai, hosts, origins, started) except (ClientGone, ConnectionError) as e: handler.close_connection = True when = e.args[0] if isinstance(e, ClientGone) else "before its answer was sent" log.info("%s %s: the client gave up after %.0f s, %s", handler.command, handler.path, time.monotonic() - started, when) def _serve(handler, ai, hosts: set[str], origins: set[str], started: float) -> None: key, rest = match(handler.path) try: body = _read_body(handler) # before any answer: unread data would reset the connection on Windows except BodyError as e: _error(handler, e.status, str(e)) return if handler.headers.get("Host") not in hosts: _error(handler, 403, "forbidden host") return origin = handler.headers.get("Origin") if origin is not None and origin not in origins: _error(handler, 403, f"web pages of {origin} may not use The Kurgan's AI servers") return # An or