# -*- coding: utf-8 -*- """ VANIGW — OpenAI-compatible gateway over Vani.ai free-account pool. Python 3.11+, stdlib only. Port 8500. Features (all reverse-engineered from c.vani.ai, Oct 2026): POST /v1/chat/completions — 37 chat models (GPT-6.x, Claude Opus 5.x, Kimi K3, GLM, Grok, Gemini, Qwen, DeepSeek...) POST /v1/images/generations — gpt-image-2.5 / gemini-3.1-flash-image / jimeng-image-4.0 / grok-imagine-image-2.0 POST /v1/audio/speech — inworld/realtime-tts-2 (voice: Alex) POST /v1/videos/generations — seedance-2.0-mini / 2.0-fast-vip / 2.0-vip / 2.5 / grok-imagine-video-1.5 (async) GET /v1/videos/{gen_id} — poll status, get mp4 POST /v1/research — Deep Research (plan -> cited report, minutes) GET /v1/research/{job_id} — poll; ?format=md|pdf|docx|html|pptx GET /v1/models — live catalog GET /media/{token} — raw attachment bytes (png/mp4/mp3) GET / — dashboard Auth: header X-Gateway-Key: vani-local-2026 (or Authorization: Bearer vani-local-2026) Pool: vani_accounts.jsonl (register with vani_reg.py), state in vanigw_state.json """ import json, sys, time, uuid, base64, threading, mimetypes import urllib.request, urllib.error, http.cookiejar from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer sys.stdout.reconfigure(encoding='utf-8') PORT = 8500 GW_KEY = 'vani-' + 'local-2026' BASE = 'https://c.vani.ai' UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36') import os as _os _ROOT = _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__))) ACCOUNTS_FILE = _os.environ.get('VANI_ACCOUNTS', _os.path.join(_ROOT, 'vani_accounts.jsonl')) STATE_FILE = _os.environ.get('VANI_STATE', _os.path.join(_ROOT, 'vanigw_state.json')) DEFAULT_CHAT = 'openai/gpt-6.1-sol' DEFAULT_IMAGE = 'google/gemini-3.1-flash-image' # cheapest; gpt-image-2.5 burns ~30% weekly DEFAULT_VIDEO = 'bytedance/seedance-2.0-mini' DEFAULT_TTS = 'inworld/realtime-tts-2' class Rotate(Exception): """account unusable for this request — try next""" class Account: def __init__(self, email, cookies): self.email = email self.cookies = cookies self.jar = http.cookiejar.CookieJar() self._load_jar(cookies) self.op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.jar)) self.lock = threading.Lock() # free plan: 1 concurrent per account self.exhausted = False # weekly limit hit self.dead = False # auth failed after refresh self.weekly_pct = None self.last_err = '' def _load_jar(self, cookies): for c in cookies: try: self.jar.set_cookie(http.cookiejar.Cookie( 0, c['name'], c['value'], None, False, c['domain'], True, c['domain'].startswith('.'), c['path'], True, c.get('secure', True), int(c.get('expires', 0) or 0), False, None, None, {})) except Exception: pass def dump_cookies(self): out = [] for c in self.jar: out.append({'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path, 'secure': bool(c.secure), 'httpOnly': bool(c.has_nonstandard_attr('HttpOnly')) or c.name.startswith('sb-'), 'expires': c.expires}) return out def refresh(self): """hit site root — Next middleware rotates sb-*-auth-token via refresh_token (30d)""" try: r = urllib.request.Request(BASE + '/', headers={'User-Agent': UA, 'Accept': 'text/html'}) self.op.open(r, timeout=45).read(200) return True except Exception: return False def req(self, method, path, body=None, raw=False, timeout=180, stream=False): data = json.dumps(body).encode() if body is not None else (b'{}' if method == 'POST' else None) hdrs = {'User-Agent': UA, 'Content-Type': 'application/json', 'Origin': BASE, 'Referer': BASE + '/chat', 'Accept': '*/*', 'Idempotency-Key': str(uuid.uuid4())} r = urllib.request.Request(BASE + path, data=data, method=method, headers=hdrs) try: resp = self.op.open(r, timeout=timeout) except urllib.error.HTTPError as e: msg = '' try: msg = e.read().decode(errors='replace')[:300] except Exception: pass if e.code == 401: if self.refresh(): try: r2 = urllib.request.Request(BASE + path, data=data, method=method, headers=hdrs) resp = self.op.open(r2, timeout=timeout) except urllib.error.HTTPError as e2: self.dead = True; self.last_err = f'401 after refresh' raise Rotate(f'{self.email}: dead (401)') else: self.dead = True; self.last_err = '401, refresh failed' raise Rotate(f'{self.email}: dead (401)') elif e.code == 429 or 'weekly_limit' in msg or 'allowance' in msg: self.exhausted = True; self.last_err = 'weekly limit' raise Rotate(f'{self.email}: weekly exhausted') elif e.code == 403: self.last_err = msg[:120] raise Rotate(f'{self.email}: 403 {msg[:100]}') else: raise VaniError(e.code, msg) if stream: return resp out = resp.read() return out if raw else json.loads(out.decode()) class VaniError(Exception): def __init__(self, code, msg): self.code = code; self.msg = msg super().__init__(f'{code}: {msg}') class Pool: def __init__(self): self.accounts = [] self.lock = threading.Lock() self.state = {'media': {}, 'exhausted': [], 'dead': []} try: self.state = json.load(open(STATE_FILE, encoding='utf-8')) self.state.setdefault('media', {}); self.state.setdefault('exhausted', []); self.state.setdefault('dead', []) except Exception: pass self.load() def load(self): seen = {} for line in open(ACCOUNTS_FILE, encoding='utf-8'): try: r = json.loads(line) except Exception: continue if r.get('ok') and r.get('cookies'): seen[r['email']] = r # last record wins (freshest cookies) with self.lock: self.accounts = [] for email, r in seen.items(): a = Account(email, r['cookies']) if email in self.state['exhausted']: a.exhausted = True if email in self.state['dead']: a.dead = True self.accounts.append(a) return len(self.accounts) def save_state(self): with self.lock: self.state['exhausted'] = [a.email for a in self.accounts if a.exhausted] self.state['dead'] = [a.email for a in self.accounts if a.dead] tmp = STATE_FILE + '.tmp' json.dump(self.state, open(tmp, 'w', encoding='utf-8')) import os; os.replace(tmp, STATE_FILE) def persist_cookies(self, acc): """save refreshed cookies back to accounts file (append fresh record)""" try: rec = {'email': acc.email, 'ok': True, 'ts': time.time(), 'cookies': acc.dump_cookies(), 'src': 'gw-refresh'} with open(ACCOUNTS_FILE, 'a', encoding='utf-8') as f: f.write(json.dumps(rec) + '\n') except Exception: pass def pick(self, need_fresh=False): with self.lock: cands = [a for a in self.accounts if not a.dead and not a.exhausted] if not cands: # weekly reset attempt: clear exhausted older than 7 days is manual; report raise VaniError(503, 'pool exhausted (all accounts dead or weekly-limited); register more with vani_reg.py') cands.sort(key=lambda a: a.weekly_pct if a.weekly_pct is not None else 0) return cands[0] def run(self, fn, max_tries=6): """run fn(account) with rotation""" tried = set() last = None for _ in range(max_tries): acc = self.pick() if acc.email in tried: # pick next unused with self.lock: alt = [a for a in self.accounts if not a.dead and not a.exhausted and a.email not in tried] if not alt: break acc = alt[0] tried.add(acc.email) try: with acc.lock: return fn(acc) except Rotate as e: last = e self.save_state() continue raise VaniError(503, f'no usable account: {last}') POOL = Pool() # ---------------- helpers ---------------- CATALOG = {'slugs': [], 'fetched': 0} def fetch_catalog(): if time.time() - CATALOG['fetched'] < 3600 and CATALOG['slugs']: return CATALOG['slugs'] try: def _f(acc): return acc.req('GET', '/api/onboarding/guide?kind=all') d = POOL.run(_f) slugs = [c['model'] for c in d.get('cards', []) if c.get('enabled')] if slugs: CATALOG['slugs'] = slugs; CATALOG['fetched'] = time.time() except Exception: pass return CATALOG['slugs'] def resolve_model(m, kind='chat'): slugs = fetch_catalog() if not m: return {'chat': DEFAULT_CHAT, 'image': DEFAULT_IMAGE, 'video': DEFAULT_VIDEO, 'audio': DEFAULT_TTS}[kind] if m in slugs: return m m2 = m.replace('vani/', '').replace('vani-', '') for s in slugs: if s == m2 or s.endswith('/' + m2) or s.split('/')[-1] == m2: return s for s in slugs: if m2.lower() in s.lower(): return s return m if '/' in m else {'chat': DEFAULT_CHAT, 'image': DEFAULT_IMAGE, 'video': DEFAULT_VIDEO, 'audio': DEFAULT_TTS}[kind] def new_conv(acc, title): return acc.req('POST', '/api/chat/conversations', {'title': title[:80]})['id'] def create_gen(acc, payload): return acc.req('POST', '/api/chat/generations', payload, timeout=60) def poll_gen(acc, gid, max_wait=600, interval=4): t0 = time.time() while time.time() - t0 < max_wait: g = acc.req('GET', f'/api/chat/generations/{gid}', timeout=60) st = g.get('status') if st == 'succeeded': return g if st in ('failed', 'error', 'cancelled'): raise VaniError(502, f'generation {st}: {g.get("error")}') time.sleep(interval) raise VaniError(504, 'generation timeout') def get_attachment(acc, att_id): return acc.req('GET', f'/api/chat/attachments/{att_id}/url', raw=True, timeout=300) def register_media(gid, email, att_id, kind): POOL.state['media'][gid] = {'email': email, 'att': att_id, 'kind': kind, 'ts': time.time()} POOL.save_state() def account_by_email(email): for a in POOL.accounts: if a.email == email: return a return None # ---------------- features ---------------- def feat_chat(payload): model = resolve_model(payload.get('model'), 'chat') msgs = payload.get('messages') or [] stream = bool(payload.get('stream')) vmsgs = [{'role': m.get('role', 'user'), 'content': m.get('content', '')} for m in msgs if isinstance(m.get('content'), str)] if not vmsgs: vmsgs = [{'role': 'user', 'content': 'Hello'}] def _run(acc): cid = new_conv(acc, vmsgs[-1]['content'][:60] or 'gw chat') body = {'model': model, 'tool_execution': 'confirm', 'media_prompt_mode': 'enhance', 'conversation_id': cid, 'reasoning_effort': payload.get('reasoning_effort', 'high'), 'vani_mode': 'standard', 'messages': vmsgs} resp = acc.req('POST', '/api/chat/stream', body, timeout=600, stream=True) if stream: return ('stream', resp, model) text = [] usage = {} for line in resp: line = line.decode('utf-8', 'replace').strip() if not line.startswith('data: '): continue try: d = json.loads(line[6:]) except Exception: continue t = d.get('type') if t == 'content.delta': text.append(d.get('text', '')) elif t == 'usage': usage = {'prompt_tokens': d.get('prompt_tokens', 0), 'completion_tokens': d.get('completion_tokens', 0)} acc.weekly_pct = d.get('weekly_used_percent') elif t == 'message.complete': break return ('full', ''.join(text), usage, model) return POOL.run(_run) def feat_image(payload): prompt = payload.get('prompt', '') if not prompt: raise VaniError(400, 'prompt required') model = resolve_model(payload.get('model'), 'image') variant = payload.get('size') or payload.get('variant') or '1024x1024' n = min(int(payload.get('n', 1)), 4) outs = [] for i in range(n): def _run(acc): cid = new_conv(acc, 'gw image') g = create_gen(acc, {'kind': 'image', 'conversation_id': cid, 'model': model, 'prompt': prompt, 'variant': variant, 'mode': 'generate'}) gid = g['id'] g2 = poll_gen(acc, gid, max_wait=300, interval=3) data = get_attachment(acc, g2['attachment_id']) register_media(gid, acc.email, g2['attachment_id'], 'image') return gid, data gid, data = POOL.run(_run) outs.append({'gid': gid, 'data': data}) return outs def feat_speech(payload): text = payload.get('input') or payload.get('prompt') or '' if not text: raise VaniError(400, 'input required') model = resolve_model(payload.get('model'), 'audio') voice = payload.get('voice') or 'Alex' def _run(acc): cid = new_conv(acc, 'gw audio') g = create_gen(acc, {'kind': 'audio', 'conversation_id': cid, 'model': model, 'variant': voice, 'prompt': text, 'mode': 'text_to_speech'}) g2 = poll_gen(acc, g['id'], max_wait=180, interval=2) data = get_attachment(acc, g2['attachment_id']) register_media(g['id'], acc.email, g2['attachment_id'], 'audio') return g['id'], data return POOL.run(_run) def feat_video_create(payload): prompt = payload.get('prompt', '') if not prompt: raise VaniError(400, 'prompt required') model = resolve_model(payload.get('model'), 'video') dur = int(payload.get('duration_secs') or payload.get('duration') or 5) ratio = payload.get('ratio') or payload.get('size') or '16:9' variant = payload.get('variant') or '720p' def _run(acc): cid = new_conv(acc, 'gw video') g = create_gen(acc, {'kind': 'video', 'conversation_id': cid, 'model': model, 'prompt': prompt, 'duration_secs': dur, 'ratio': ratio, 'mode': 'text_to_video', 'variant': variant}) POOL.state['media'][g['id']] = {'email': acc.email, 'att': None, 'kind': 'video', 'ts': time.time()} POOL.save_state() return {'id': g['id'], 'status': g['status'], 'model': model, 'conversation_id': cid} return POOL.run(_run) def feat_video_status(gid): info = POOL.state['media'].get(gid) if not info: raise VaniError(404, 'unknown video id') acc = account_by_email(info['email']) if not acc: raise VaniError(500, 'owner account gone from pool') with acc.lock: g = acc.req('GET', f'/api/chat/generations/{gid}', timeout=60) st = g.get('status') out = {'id': gid, 'status': st, 'model': g.get('params', {}).get('model')} if st == 'succeeded': info['att'] = g['attachment_id'] POOL.save_state() out['url'] = f'/media/{gid}.mp4' if g.get('params'): out['params'] = g['params'] elif st in ('failed', 'error'): out['error'] = g.get('error') return out def feat_research_create(payload): query = payload.get('query') or payload.get('prompt') or '' if not query: raise VaniError(400, 'query required') def _run(acc): cid = new_conv(acc, query[:60]) j = acc.req('POST', '/api/chat/research/v2', {'conversation_id': cid, 'query': query}) POOL.state['media']['res:' + j['id']] = {'email': acc.email, 'cid': cid, 'kind': 'research', 'ts': time.time()} POOL.save_state() return {'id': j['id'], 'status': j['status'], 'conversation_id': cid} return POOL.run(_run) def feat_research_status(jid, fmt='json'): info = POOL.state['media'].get('res:' + jid) if not info: raise VaniError(404, 'unknown research id') acc = account_by_email(info['email']) with acc.lock: j = acc.req('GET', f'/api/chat/research/v2/{jid}', timeout=60) st = j.get('status') # auto-advance try: if st == 'awaiting_approval': j = acc.req('POST', f'/api/chat/research/v2/{jid}/start', {}) st = j.get('status') elif st == 'awaiting_answers': j = acc.req('POST', f'/api/chat/research/v2/{jid}/answers', {'skip': True}) st = j.get('status') except VaniError: pass out = {'id': jid, 'status': st, 'title': j.get('title'), 'error': j.get('error_code')} if st == 'succeeded' and j.get('artifact_id'): out['artifact_id'] = j['artifact_id'] if fmt and fmt != 'json': data = acc.req('GET', f"/api/artifacts/{j['artifact_id']}/export?format={fmt}", raw=True, timeout=120) out['content_type'] = {'md': 'text/markdown', 'html': 'text/html', 'pdf': 'application/pdf', 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'pptx': 'application/vnd.openxmlformats-officedocument.pptx'}.get(fmt, 'application/octet-stream') out['raw'] = data else: art = acc.req('GET', f"/api/artifacts/{j['artifact_id']}", timeout=60) out['report_preview'] = art.get('artifact', {}).get('preview') out['formats'] = art.get('artifact', {}).get('formats') return out # ---------------- HTTP server ---------------- DASH = """
| account | status | weekly % | last err |
|---|
curl http://127.0.0.1:8500/v1/chat/completions -H "X-Gateway-Key: """ + GW_KEY + """" -H "Content-Type: application/json" \\
-d '{"model":"claude-opus-5","messages":[{"role":"user","content":"hi"}]}'
curl http://127.0.0.1:8500/v1/images/generations -H "X-Gateway-Key: """ + GW_KEY + """" -H "Content-Type: application/json" \\
-d '{"prompt":"red cube on white"}' # -> b64_json + /media url
curl http://127.0.0.1:8500/v1/audio/speech -H "X-Gateway-Key: """ + GW_KEY + """" -H "Content-Type: application/json" \\
-d '{"input":"Hello world"}' --output voice.mp3
curl http://127.0.0.1:8500/v1/videos/generations -H "X-Gateway-Key: """ + GW_KEY + """" -H "Content-Type: application/json" \\
-d '{"prompt":"ocean wave at sunset"}' # -> {"id":...}; poll GET /v1/videos/{id}
curl http://127.0.0.1:8500/v1/research -H "X-Gateway-Key: """ + GW_KEY + """" -H "Content-Type: application/json" \\
-d '{"query":"state of LLM inference optimization 2026"}' # poll GET /v1/research/{id}?format=md