#!/usr/bin/env python3 """One HTTP request to one upstream, with the API key added. Run inetd style: the accepted connection is fd 0. systemd gives it with Accept=yes and StandardInput=socket; launchd with inetdCompatibility. Whoever can connect may use the key for inference at UPSTREAM, and for nothing else: the proxy forwards only to that base URL, and it replaces any Authorization header the client sends. usage: llm-proxy.py UPSTREAM_BASE_URL KEY_FILE e.g. llm-proxy.py https://openrouter.ai/api/v1 /run/credentials/.../llm-key Requests for /v1/ go to UPSTREAM_BASE_URL/. """ import logging from http.server import BaseHTTPRequestHandler from urllib.parse import urlsplit HOP_BY_HOP = { "connection", "keep-alive", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "host", "authorization", "content-length", } def make_handler(base_path: str, connect_upstream, key: str): """A request handler that forwards /v1/ to base_path/, over a connection from `connect_upstream()`, with `key`.""" class Proxy(BaseHTTPRequestHandler): protocol_version = "HTTP/1.0" # one request, then close def _forward(self): if not (self.path == "/v1" or self.path.startswith("/v1/")): self.send_error(404, "only /v1/ is proxied") return path = base_path.rstrip("/") + self.path[len("/v1"):] length = int(self.headers.get("content-length") or 0) body = self.rfile.read(length) if length else None headers = { k: v for k, v in self.headers.items() if k.lower() not in HOP_BY_HOP } headers["Authorization"] = f"Bearer {key}" conn = connect_upstream() conn.request(self.command, path, body=body, headers=headers) resp = conn.getresponse() self.send_response(resp.status, resp.reason) for k, v in resp.getheaders(): if k.lower() not in HOP_BY_HOP: self.send_header(k, v) self.end_headers() # stream, so server-sent events arrive as they come while chunk := resp.read1(65536): self.wfile.write(chunk) self.wfile.flush() do_GET = do_POST = _forward def log_message(self, format, *args): logging.info(format, *args) return Proxy def main(argv, cwd, connection, https): """Serve the one `connection`, forwarding to argv's upstream, and only there.""" _, upstream, key_file = argv base = urlsplit(upstream) if base.scheme != "https": raise SystemExit(f"upstream must be https: {upstream}") key = (cwd / key_file).read_text(encoding="utf-8").strip() make_handler(base.path, lambda: https(base.netloc, timeout=600), key)( connection, ("local", 0), None) if __name__ == "__main__": def _script_io(): import http.client import socket import sys from pathlib import Path return main( argv=list(sys.argv), cwd=Path.cwd(), # inetd style: the accepted connection is fd 0 connection=socket.socket(fileno=0), https=http.client.HTTPSConnection, ) raise SystemExit(_script_io())