#!/usr/bin/env python3 """A chat endpoint that behaves like those that follow the OpenAI contract. OpenAI's streaming API sends the `usage` chunk only when the request asked for it with stream_options.include_usage. This endpoint does the same, so a client that forgets the field gets no token counts at all - which is the shape that left splinter's stats.last_in at 0 and stopped automatic compaction. It answers /v1/models so a caller can wait for it, and appends one line per completion request to the log: REQ bytes= msgs= include_usage= """ import http.server import json import sys PORT = int(sys.argv[1]) LOG = sys.argv[2] # The prompt size it reports. Past a realistic compact_threshold on purpose. PROMPT_TOKENS = 90000 class Handler(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def do_GET(self): body = json.dumps({"data": [{"id": "m", "object": "model"}]}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.send_header("Connection", "close") self.end_headers() self.close_connection = True self.wfile.write(body) def do_POST(self): n = int(self.headers.get("content-length") or 0) raw = self.rfile.read(n) try: req = json.loads(raw) except ValueError: req = {} asked = bool((req.get("stream_options") or {}).get("include_usage")) with open(LOG, "a") as log: log.write("REQ bytes=%d msgs=%d include_usage=%s\n" % (len(raw), len(req.get("messages") or []), asked)) self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Connection", "close") self.end_headers() # No keep-alive: a client waits for the close after [DONE], and a # lingering connection would keep the turn "running" forever. self.close_connection = True def event(obj): self.wfile.write(b"data: " + json.dumps(obj).encode() + b"\n\n") self.wfile.flush() event({"choices": [{"delta": {"content": "ok"}, "index": 0}]}) final = {"choices": [{"delta": {}, "finish_reason": "stop", "index": 0}]} if asked: final["usage"] = {"prompt_tokens": PROMPT_TOKENS, "completion_tokens": 5} event(final) self.wfile.write(b"data: [DONE]\n\n") self.wfile.flush() def log_message(self, *args): pass http.server.HTTPServer(("127.0.0.1", PORT), Handler).serve_forever()