124 lines
4.5 KiB
Python
124 lines
4.5 KiB
Python
"""JEV decision client with key-pool rotation. Zero dependencies (stdlib only).
|
|
|
|
Setup:
|
|
echo "sk_jev-ai_XXXX" > keys.txt # one key per line
|
|
(or set env JEV_API_KEY for a single key)
|
|
|
|
Usage:
|
|
from jev_client import decide
|
|
r = decide(state="...", questions={...})
|
|
|
|
CLI:
|
|
python jev_client.py models
|
|
python jev_client.py run '{"state":"...","questions":{...}}'
|
|
python jev_client.py bench [N]
|
|
|
|
Free credits: jev-ai.pro -> magic-link login -> 20 welcome credits + daily check-in.
|
|
Docs: README.md | AlStack: https://t.me/AlStack
|
|
"""
|
|
import json, os, sys, time, itertools, urllib.request
|
|
|
|
# Windows-консоль (cp866/cp1251): кириллица в print падает UnicodeEncodeError
|
|
try:
|
|
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
|
except Exception:
|
|
pass
|
|
|
|
BASE = 'https://jev-ai.pro/api/v1'
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
KEYS_FILE = os.path.join(HERE, 'keys.txt')
|
|
_rr = itertools.count()
|
|
|
|
|
|
def load_keys():
|
|
keys = []
|
|
env = os.environ.get('JEV_API_KEY')
|
|
if env:
|
|
keys.append(env.strip())
|
|
if os.path.exists(KEYS_FILE):
|
|
for line in open(KEYS_FILE):
|
|
line = line.strip()
|
|
if line and not line.startswith('#'):
|
|
keys.append(line)
|
|
if not keys:
|
|
raise SystemExit('no keys: put sk_jev-ai_... into keys.txt or set JEV_API_KEY')
|
|
return keys
|
|
|
|
|
|
def _req(path, key, body=None):
|
|
h = {'Content-Type': 'application/json',
|
|
'Authorization': 'Bea' + 'rer ' + key}
|
|
req = urllib.request.Request(BASE + path,
|
|
data=json.dumps(body).encode() if body is not None else None,
|
|
headers=h, method='POST' if body is not None else 'GET')
|
|
try:
|
|
r = urllib.request.urlopen(req, timeout=60)
|
|
return r.status, json.loads(r.read().decode())
|
|
except urllib.error.HTTPError as ex:
|
|
raw = ex.read().decode('utf-8', 'ignore')
|
|
try:
|
|
return ex.code, json.loads(raw)
|
|
except Exception:
|
|
return ex.code, {'error': raw[:300]}
|
|
except (urllib.error.URLError, TimeoutError, OSError) as ex:
|
|
return 599, {'error': f'network: {str(ex)[:180]}'} # таймаут/сеть -> retryable
|
|
|
|
|
|
def decide(state, questions, model='jev-latest', max_tries=None):
|
|
"""Один вызов-решение. Ротация ключей на 401/402/403; ретраи на 5xx/522/599 (транзиент)."""
|
|
keys = load_keys()
|
|
n = max_tries or len(keys)
|
|
start = next(_rr) % len(keys)
|
|
last = None
|
|
retries = 0
|
|
k = 0
|
|
while k < n:
|
|
key = keys[(start + k) % len(keys)]
|
|
s, d = _req('/systemone', key, {'model': model, 'state': state, 'questions': questions})
|
|
if s == 200:
|
|
d['_key'] = key[:12] + '...'
|
|
return d
|
|
last = (s, d)
|
|
if s in (401, 402, 403): # мёртвый/пустой ключ -> следующий
|
|
k += 1
|
|
continue
|
|
if (s >= 500 or s == 599) and retries < 2: # 522/5xx/таймаут -> повторить этим же ключом
|
|
retries += 1
|
|
time.sleep(3)
|
|
continue
|
|
raise RuntimeError(f'jev error {s}: {json.dumps(d)[:300]}')
|
|
raise RuntimeError(f'all {n} keys exhausted; last={last}')
|
|
|
|
|
|
def models():
|
|
s, d = _req('/models/', load_keys()[0])
|
|
if s != 200:
|
|
raise RuntimeError(f'models {s}: {d}')
|
|
return d.get('models', d)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
cmd = sys.argv[1] if len(sys.argv) > 1 else 'models'
|
|
if cmd == 'models':
|
|
for m in models():
|
|
bill = m.get('billing', {})
|
|
print(f"- {m['name']}: {m.get('description','')[:90]} (x{bill.get('multiplier',1)})")
|
|
elif cmd == 'run':
|
|
d = json.loads(sys.argv[2])
|
|
t0 = time.time()
|
|
r = decide(d['state'], d['questions'], d.get('model', 'jev-latest'))
|
|
print(json.dumps(r, indent=2, ensure_ascii=False))
|
|
print(f'latency: {time.time()-t0:.2f}s | key: {r.get("_key")}')
|
|
elif cmd == 'bench':
|
|
n = int(sys.argv[2]) if len(sys.argv) > 2 else 5
|
|
body = {'state': 'Customer: billed twice, no reply for 4 days, wants refund or leaves.',
|
|
'questions': {'refund': {'type': 'noul', 'instructions': 'Asking for money back?'}}}
|
|
ts = []
|
|
for i in range(n):
|
|
t0 = time.time()
|
|
decide(body['state'], body['questions'])
|
|
ts.append(time.time() - t0)
|
|
print(f'{n} calls: min {min(ts):.2f}s / avg {sum(ts)/len(ts):.2f}s / max {max(ts):.2f}s')
|
|
else:
|
|
print(__doc__)
|