Upload 3 files
Browse filesFiles changed (3)
- demo/__init__.pyAdded
- demo/index.htmlAdded+98
- demo/server.pyAdded+107
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>RightNow Mini, side by side</title><style> :root { --ink: #1b1a17; --paper: #f6f1e7; --line: #cfc6b4; --soft: #6b655a; --go: #1b1a17; } * { box-sizing: border-box; } body { margin: 0; background: var(--paper); color: var(--ink); font: 16px/1.5 ui-sans-serif, system-ui, "Segoe UI", sans-serif; } main { max-width: 1180px; margin: 0 auto; padding: 28px 20px 60px; } h1 { font-size: 28px; margin: 0 0 4px; letter-spacing: -0.01em; } p.sub { margin: 0 0 20px; color: var(--soft); } textarea { width: 100%; min-height: 96px; padding: 12px; border: 1px solid var(--line); border-radius: 8px; background: #fffdf8; color: var(--ink); font: inherit; resize: vertical; } .row { display: flex; gap: 10px; align-items: center; margin: 10px 0 20px; flex-wrap: wrap; } button { padding: 10px 18px; border: 1px solid var(--go); border-radius: 8px; background: var(--go); color: var(--paper); font: inherit; cursor: pointer; } button[disabled] { opacity: .5; cursor: default; } button.ghost { background: transparent; color: var(--ink); border-color: var(--line); } .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; } @media (max-width: 820px) { .grid { grid-template-columns: 1fr; } } .pane { border: 1px solid var(--line); border-radius: 10px; background: #fffdf8; display: flex; flex-direction: column; min-height: 420px; } .head { padding: 12px 14px; border-bottom: 1px solid var(--line); display: flex; justify-content: space-between; gap: 12px; align-items: baseline; } .name { font-weight: 600; } .nums { font-variant-numeric: tabular-nums; color: var(--soft); white-space: nowrap; } .nums b { color: var(--ink); font-size: 20px; } pre { margin: 0; padding: 14px; white-space: pre-wrap; word-break: break-word; font: 13.5px/1.5 ui-monospace, Consolas, monospace; flex: 1; overflow: auto; max-height: 560px; } pre .think { color: var(--soft); } .note { color: var(--soft); font-size: 13.5px; margin-top: 16px; }</style></head><body><main> <h1>RightNow Mini, side by side</h1> <p class="sub">The same coding task goes to both models at the same moment. The numbers are measured in your browser from what arrives.</p> <textarea id="task">Write a Python function that merges overlapping intervals, with type hints and five unit tests.</textarea> <div class="row"> <button id="go">Run both</button> <button class="ghost" data-t="Write a thread-safe LRU cache in Python with O(1) get and put, and explain the locking.">LRU cache</button> <button class="ghost" data-t="Find and fix the bug: def median(xs): xs.sort(); n = len(xs); return xs[n // 2] if n % 2 else (xs[n // 2] + xs[n // 2 + 1]) / 2">Fix a bug</button> <button class="ghost" data-t="Write a SQL query and a short explanation: the three customers with the highest total order value in each country, from tables customers(id, country) and orders(customer_id, value).">SQL</button> </div> <div class="grid"> <section class="pane"><div class="head"><span class="name" id="n-mini">RightNow Mini</span><span class="nums"><b id="tps-mini">0</b> tok/s · <span id="s-mini">0.0</span> s · <span id="tok-mini">0</span> tokens</span></div><pre id="out-mini"></pre></section> <section class="pane"><div class="head"><span class="name" id="n-other">Other model</span><span class="nums"><b id="tps-other">0</b> tok/s · <span id="s-other">0.0</span> s · <span id="tok-other">0</span> tokens</span></div><pre id="out-other"></pre></section> </div> <p class="note">Seconds run from the click to the last token. Tokens per second is the model's own count of output tokens when the stream reports it, otherwise the number of stream pieces, divided by the seconds since the first one. Grey text is the model's reasoning.</p></main><script>const $ = id => document.getElementById(id);fetch('/info').then(r => r.json()).then(i => { $('n-mini').textContent = 'RightNow Mini (' + i.mini + ')'; $('n-other').textContent = i.other; });document.querySelectorAll('button[data-t]').forEach(b => b.onclick = () => { $('task').value = b.dataset.t; });
async function run(side, task) { const out = $('out-' + side); out.textContent = ''; const t0 = performance.now(); let first = 0, pieces = 0, usage = 0, done = false; const tick = setInterval(() => { const now = performance.now(); $('s-' + side).textContent = ((now - t0) / 1000).toFixed(1); const n = usage || pieces; $('tok-' + side).textContent = n; if (first && now > first) $('tps-' + side).textContent = Math.round(n / ((now - first) / 1000)); if (done) clearInterval(tick); }, 100); try { const r = await fetch('/stream/' + side, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ task }) }); if (!r.ok) { out.textContent = await r.text(); return; } const reader = r.body.getReader(); const dec = new TextDecoder(); let buf = ''; for (;;) { const { value, done: end } = await reader.read(); if (end) break; buf += dec.decode(value, { stream: true }); let i; while ((i = buf.indexOf('\n')) >= 0) { const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1); if (!line.startsWith('data:')) continue; const data = line.slice(5).trim(); if (data === '[DONE]') continue; let d; try { d = JSON.parse(data); } catch (e) { continue; } if (d.error) { out.append(document.createTextNode('\n[' + (d.error.message || d.error) + ']')); continue; } if (d.usage && d.usage.completion_tokens) usage = d.usage.completion_tokens; for (const c of d.choices || []) { const dl = c.delta || {}; const think = dl.reasoning_content || dl.reasoning || ''; const text = dl.content || ''; if (think || text) { if (!first) first = performance.now(); pieces++; } if (think) { const s = document.createElement('span'); s.className = 'think'; s.textContent = think; out.append(s); } if (text) out.append(document.createTextNode(text)); } out.scrollTop = out.scrollHeight; } } } catch (e) { out.append(document.createTextNode('\n[' + e + ']')); } finally { done = true; }}$('go').onclick = async () => { const task = $('task').value.trim(); if (!task) return; $('go').disabled = true; await Promise.all([run('mini', task), run('other', task)]); $('go').disabled = false;};</script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107"""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 tokensper 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 argparseimport jsonimport osimport time
import aiohttpfrom 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()demo/__init__.pyAdded
demo/index.htmlAdded+98
demo/server.pyAdded+107