motif64

m64_13c6eecfdd13 / llm_relay.py

112 lines, 4.8 KBraw
1"""Loopback LLM relay for the agent harness (stdlib only).23The harness (pi, hermes, ...) is configured with http://127.0.0.1:9000/v1 as an4OpenAI-compatible provider. This relay forwards POST /v1/chat/completions to5http://openrouter.ai/api/v1/chat/completions with the model forced to $UPSTREAM_MODEL,6through the m64 gate (HTTP_PROXY): the gate adds the OpenRouter key and goes on over TLS,7so the key never enters the container. Streams (SSE) are relayed chunk by chunk.8Taken from the deepseek-flash-openrouter-gb10 capsule's server.py; binds 127.0.0.1 only.9"""1011import json12import os13import sys14import urllib.error15import urllib.request16from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer1718PORT = int(os.environ.get("RELAY_PORT", "9000"))19UPSTREAM = "http://openrouter.ai/api/v1/chat/completions"  # plain http: the gate does TLS20UPSTREAM_MODEL = os.environ["UPSTREAM_MODEL"]21PUBLIC_MODEL = os.environ["AGENT_MODEL"]22MAX_BODY = 32 * 1024 * 102423TIMEOUT_S = 900  # between two bytes from upstream (a long reasoning pause is fine)24CHUNK = 16 * 10242526# urllib's ProxyHandler reads HTTP_PROXY from the environment: every call goes via the gate.27OPENER = urllib.request.build_opener(urllib.request.ProxyHandler())282930class Handler(BaseHTTPRequestHandler):31    protocol_version = "HTTP/1.1"32    server_version = "llm-relay"3334    def log_message(self, fmt, *args):  # one short line per request on stderr (not /health)35        if self.path == "/health":36            return37        sys.stderr.write("%s %s\n" % (self.command, fmt % args))3839    def _json(self, status, obj):40        data = json.dumps(obj).encode()41        self.send_response(status)42        self.send_header("Content-Type", "application/json")43        self.send_header("Content-Length", str(len(data)))44        self.end_headers()45        self.wfile.write(data)4647    def do_GET(self):48        if self.path == "/health":49            return self._json(200, {"status": "ok"})50        if self.path == "/v1/models":51            return self._json(200, {"object": "list", "data": [52                {"id": PUBLIC_MODEL, "object": "model", "created": 0, "owned_by": "openrouter",53                 "upstream": UPSTREAM_MODEL},54            ]})55        return self._json(404, {"error": "not found"})5657    def do_POST(self):58        if self.path != "/v1/chat/completions":59            return self._json(404, {"error": "not found"})60        try:61            length = int(self.headers.get("Content-Length") or 0)62        except ValueError:63            return self._json(400, {"error": "bad Content-Length"})64        if length <= 0 or length > MAX_BODY:65            return self._json(400 if length <= 0 else 413, {"error": "body missing or too large"})66        try:67            body = json.loads(self.rfile.read(length))68        except ValueError:69            return self._json(400, {"error": "body must be JSON"})70        if not isinstance(body, dict):71            return self._json(400, {"error": "body must be a JSON object"})72        body["model"] = UPSTREAM_MODEL73        req = urllib.request.Request(UPSTREAM, data=json.dumps(body).encode(), method="POST", headers={74            "Content-Type": "application/json",75            "Accept": "text/event-stream" if body.get("stream") is True else "application/json",76            "X-Title": os.environ.get("RELAY_TITLE", "m64 agent capsule"),77            # No Authorization: the gate sets it (Bearer <key>) for openrouter.ai.78        })79        try:80            resp = OPENER.open(req, timeout=TIMEOUT_S)81        except urllib.error.HTTPError as e:82            resp = e  # relay OpenRouter's own error status and body83        except (urllib.error.URLError, OSError) as e:84            return self._json(502, {"error": f"upstream unreachable: {type(e).__name__}"})85        with resp:86            self.send_response(resp.status if hasattr(resp, "status") else resp.code)87            self.send_header("Content-Type", resp.headers.get("Content-Type", "application/json"))88            self.send_header("Cache-Control", "no-cache")89            self.send_header("Transfer-Encoding", "chunked")90            self.end_headers()91            try:92                while True:93                    # read1: whatever has arrived (up to CHUNK), without waiting to fill it.94                    data = resp.read1(CHUNK) if hasattr(resp, "read1") else resp.read(CHUNK)95                    if not data:96                        break97                    self.wfile.write(b"%x\r\n%s\r\n" % (len(data), data))98                    self.wfile.flush()99                self.wfile.write(b"0\r\n\r\n")100            except (BrokenPipeError, ConnectionResetError):101                self.close_connection = True102103104def main():105    server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)106    server.daemon_threads = True107    sys.stderr.write(f"[llm-relay] 127.0.0.1:{PORT} -> {UPSTREAM_MODEL}\n")108    server.serve_forever()109110111if __name__ == "__main__":112    main()