Files

651 lines
29 KiB
Python

# -*- 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 = """<!doctype html><html><head><meta charset="utf-8"><title>VANIGW</title>
<style>
body{background:#0d1117;color:#c9d1d9;font:14px/1.5 ui-monospace,Consolas,monospace;margin:0;padding:24px}
h1{color:#58a6ff;font-size:20px} h2{color:#8b949e;font-size:14px;text-transform:uppercase;margin-top:28px}
table{border-collapse:collapse;width:100%;max-width:900px} td,th{border:1px solid #21262d;padding:4px 10px;text-align:left;font-size:13px}
th{color:#8b949e} .ok{color:#3fb950}.bad{color:#f85149}.warn{color:#d29922}
pre{background:#161b22;border:1px solid #21262d;padding:10px;overflow-x:auto;font-size:12px;max-width:900px}
a{color:#58a6ff} .foot{margin-top:40px;color:#484f58;font-size:12px}
</style></head><body>
<h1>VANIGW — Vani.ai pool gateway</h1>
<div>key: <b>""" + GW_KEY + """</b> · port 8500 · accounts: <b>__NACC__</b> · models: <b>__NMOD__</b></div>
<h2>Pool</h2><table><tr><th>account</th><th>status</th><th>weekly %</th><th>last err</th></tr>__ROWS__</table>
<h2>Quick start</h2>
<pre>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</pre>
<div class="foot">free-tier pool · register more: python vani_reg.py N · <a href="https://t.me/AlStack">t.me/AlStack</a></div>
</body></html>"""
class H(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def log_message(self, *a):
pass
def _auth(self):
k = self.headers.get('X-Gateway-Key') or ''
if not k:
ah = self.headers.get('Authorization') or ''
if ah.startswith('Bearer '):
k = ah[7:]
return k == GW_KEY
def _send(self, code, obj, ctype='application/json'):
data = obj if isinstance(obj, bytes) else json.dumps(obj, ensure_ascii=False).encode()
self.send_response(code)
self.send_header('Content-Type', ctype)
self.send_header('Content-Length', str(len(data)))
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
try:
self.wfile.write(data)
except Exception:
pass
def _err(self, code, msg):
self._send(code, {'error': {'message': str(msg)[:400], 'code': code}})
def do_OPTIONS(self):
self.send_response(204)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Headers', '*')
self.send_header('Access-Control-Allow-Methods', '*')
self.send_header('Content-Length', '0')
self.end_headers()
def do_GET(self):
path = self.path.split('?')[0]
qs = self.path.split('?')[1] if '?' in self.path else ''
if path == '/':
rows = []
for a in POOL.accounts:
cls = 'bad' if a.dead else ('warn' if a.exhausted else 'ok')
st = 'dead' if a.dead else ('weekly-limit' if a.exhausted else 'live')
rows.append(f'<tr><td>{a.email}</td><td class="{cls}">{st}</td><td>{a.weekly_pct if a.weekly_pct is not None else "?"}</td><td>{a.last_err[:60]}</td></tr>')
slugs = fetch_catalog()
html = DASH.replace('__ROWS__', ''.join(rows)).replace('__NACC__', str(len(POOL.accounts))).replace('__NMOD__', str(len(slugs)))
return self._send(200, html.encode(), 'text/html; charset=utf-8')
if not self._auth():
return self._err(401, 'bad key')
if path == '/health':
live = [a for a in POOL.accounts if not a.dead and not a.exhausted]
return self._send(200, {'status': 'ok', 'accounts': len(POOL.accounts), 'live': len(live), 'models': len(fetch_catalog())})
if path == '/v1/models':
slugs = fetch_catalog()
return self._send(200, {'object': 'list', 'data': [{'id': s, 'object': 'model'} for s in slugs]})
if path.startswith('/v1/videos/'):
gid = path.rsplit('/', 1)[1].replace('.mp4', '')
try:
return self._send(200, feat_video_status(gid))
except VaniError as e:
return self._err(e.code, e.msg)
if path.startswith('/v1/research/'):
jid = path.rsplit('/', 1)[1]
fmt = 'md'
for kv in qs.split('&'):
if kv.startswith('format='):
fmt = kv[7:]
try:
out = feat_research_status(jid, fmt if fmt != 'json' else 'json')
if 'raw' in out:
return self._send(200, out.pop('raw'), out.pop('content_type'))
return self._send(200, out)
except VaniError as e:
return self._err(e.code, e.msg)
if path.startswith('/media/'):
token = path[len('/media/'):]
gid = token.split('.')[0]
info = POOL.state['media'].get(gid)
if not info or not info.get('att'):
return self._err(404, 'media not ready')
acc = account_by_email(info['email'])
if not acc:
return self._err(500, 'owner gone')
try:
with acc.lock:
data = get_attachment(acc, info['att'])
ct = {'image': 'image/png', 'video': 'video/mp4', 'audio': 'audio/mpeg'}.get(info['kind'], 'application/octet-stream')
return self._send(200, data, ct)
except Exception as e:
return self._err(502, str(e)[:200])
return self._err(404, 'not found')
def do_POST(self):
path = self.path.split('?')[0]
if not self._auth():
return self._err(401, 'bad key')
try:
n = int(self.headers.get('Content-Length') or 0)
payload = json.loads(self.rfile.read(n) or b'{}')
except Exception:
return self._err(400, 'bad json')
try:
if path == '/v1/chat/completions':
res = feat_chat(payload)
if res[0] == 'stream':
_, resp, model = res
self.send_response(200)
self.send_header('Content-Type', 'text/event-stream')
self.send_header('Cache-Control', 'no-cache')
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Transfer-Encoding', 'chunked')
self.end_headers()
cid = 'chatcmpl-' + uuid.uuid4().hex[:24]
def chunk(s):
b = s.encode()
self.wfile.write(f'{len(b):x}\r\n'.encode() + b + b'\r\n')
try:
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':
chunk('data: ' + json.dumps({'id': cid, 'object': 'chat.completion.chunk', 'model': model,
'choices': [{'index': 0, 'delta': {'content': d.get('text', '')}, 'finish_reason': None}]}) + '\n\n')
elif t == 'message.complete':
chunk('data: ' + json.dumps({'id': cid, 'object': 'chat.completion.chunk', 'model': model,
'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]}) + '\n\n')
break
chunk('data: [DONE]\n\n')
self.wfile.write(b'0\r\n\r\n')
except Exception:
try:
self.wfile.write(b'0\r\n\r\n')
except Exception:
pass
return
_, text, usage, model = res
return self._send(200, {
'id': 'chatcmpl-' + uuid.uuid4().hex[:24], 'object': 'chat.completion', 'model': model,
'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': text}, 'finish_reason': 'stop'}],
'usage': {'prompt_tokens': usage.get('prompt_tokens', 0), 'completion_tokens': usage.get('completion_tokens', 0),
'total_tokens': usage.get('prompt_tokens', 0) + usage.get('completion_tokens', 0)}})
if path == '/v1/images/generations':
outs = feat_image(payload)
data = [{'b64_json': base64.b64encode(o['data']).decode(), 'url': f'/media/{o["gid"]}.png'} for o in outs]
return self._send(200, {'created': int(time.time()), 'data': data})
if path == '/v1/audio/speech':
gid, data = feat_speech(payload)
return self._send(200, data, 'audio/mpeg')
if path == '/v1/videos/generations':
return self._send(200, feat_video_create(payload))
if path == '/v1/research':
return self._send(200, feat_research_create(payload))
return self._err(404, 'not found')
except VaniError as e:
return self._err(e.code, e.msg)
except Exception as e:
return self._err(500, f'{type(e).__name__}: {e}')
def main():
print(f'[vanigw] pool: {len(POOL.accounts)} accounts '
f'({sum(1 for a in POOL.accounts if not a.dead and not a.exhausted)} live)')
print(f'[vanigw] catalog: {len(fetch_catalog())} models')
srv = ThreadingHTTPServer(('127.0.0.1', PORT), H)
srv.daemon_threads = True
print(f'[vanigw] listening on 127.0.0.1:{PORT}')
srv.serve_forever()
if __name__ == '__main__':
main()