"""The side-by-side demo: one coding task, two models, live speed and a wall clock. No sign-up. MINI_URL=http://127.0.0.1:9000 MINI_MODEL=rightnow-mini \ OTHER_URL=https://openrouter.ai/api OTHER_MODEL=anthropic/claude-opus-5.5 OTHER_KEY_ENV=OPENROUTER_API_KEY \ python demo/server.py --port 8700 The page talks only to this server. This server streams from the two model endpoints and adds nothing: the tokens per second and the seconds on the page are measured in the visitor's browser from the stream it receives. The other model's key is read from the environment variable named by OTHER_KEY_ENV and never sent to the browser. Limits for an open page: one task at a time per visitor address, max_tokens capped, a daily request cap. """ import argparse import json import os import time import aiohttp from aiohttp import web HERE = os.path.dirname(os.path.abspath(__file__)) STATE = {"day": "", "count": 0, "busy": set()} def side(name): if name == "mini": return os.environ.get("MINI_URL", "http://127.0.0.1:9000"), os.environ.get("MINI_MODEL", "rightnow-mini"), os.environ.get("MINI_KEY", "") key_env = os.environ.get("OTHER_KEY_ENV", "OPENROUTER_API_KEY") return os.environ.get("OTHER_URL", "https://openrouter.ai/api"), os.environ.get("OTHER_MODEL", "anthropic/claude-opus-5.5"), os.environ.get(key_env, "") async def index(request): return web.FileResponse(os.path.join(HERE, "index.html")) async def info(request): return web.json_response({"mini": side("mini")[1], "other": side("other")[1], "max_tokens": request.app["args"].max_tokens}) async def stream(request): a = request.app["args"] name = request.match_info["side"] if name not in ("mini", "other"): raise web.HTTPNotFound() body = await request.json() task = str(body.get("task", ""))[:4000] if not task.strip(): raise web.HTTPBadRequest(text="empty task") day = time.strftime("%Y-%m-%d", time.gmtime()) if STATE["day"] != day: STATE.update(day=day, count=0) who = (request.remote or "?") + ":" + name if STATE["count"] >= a.daily_cap: raise web.HTTPTooManyRequests(text="the demo's daily limit is reached") if who in STATE["busy"]: raise web.HTTPTooManyRequests(text="one task at a time") STATE["count"] += 1 STATE["busy"].add(who) url, model, key = side(name) headers = {"Content-Type": "application/json"} if key: headers["Authorization"] = "Bearer " + key payload = {"model": model, "stream": True, "max_tokens": a.max_tokens, "stream_options": {"include_usage": True}, "messages": [{"role": "user", "content": task}]} resp = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-store", "X-Accel-Buffering": "no"}) await resp.prepare(request) try: async with request.app["session"].post(url + "/v1/chat/completions", json=payload, headers=headers) as r: if r.status != 200: await resp.write(f"data: {json.dumps({'error': f'upstream answered {r.status}'})}\n\n".encode()) else: async for chunk in r.content.iter_any(): await resp.write(chunk) except (aiohttp.ClientError, ConnectionResetError) as e: try: await resp.write(f"data: {json.dumps({'error': type(e).__name__})}\n\n".encode()) except ConnectionResetError: pass finally: STATE["busy"].discard(who) return resp async def make_app(args): app = web.Application(client_max_size=2**20) app["args"] = args app["session"] = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=600)) app.router.add_get("/", index) app.router.add_get("/info", info) app.router.add_post("/stream/{side}", stream) async def close(app): await app["session"].close() app.on_cleanup.append(close) return app def main(): ap = argparse.ArgumentParser() ap.add_argument("--host", default="127.0.0.1") ap.add_argument("--port", type=int, default=8700) ap.add_argument("--max-tokens", type=int, default=2048) ap.add_argument("--daily-cap", type=int, default=2000) web.run_app(make_app(ap.parse_args()), host=ap.parse_args().host, port=ap.parse_args().port, print=None) if __name__ == "__main__": main()