commit 8b88bbceab4191c9c1f4ec3c7dd9023cb1237e5a Author: reform Date: Tue Nov 3 17:12:04 2026 +0300 chatco-autoreg: farm + pool gateway diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..c03a1fd --- /dev/null +++ b/.env.example @@ -0,0 +1,10 @@ +# 2captcha (32 hex). Можно не задавать, если есть cap.txt +CHATCO_CAP= +CHATCO_CAP_FILE=cap.txt +# пул почты: email:password по строке +CHATCO_SOIL=soil.txt +# пул аккаунтов и состояние шлюза +CHATCO_POOL=pool.jsonl +CHATCO_STATE=pool_state.json +# порт шлюза +CHATCO_PORT=8833 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..70181ba --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +pool.jsonl +pool_state.json +reserved/ +soil.txt +cap.txt +.env +.env.sh +venv/ +__pycache__/ +*.pyc +*.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..293497e --- /dev/null +++ b/README.md @@ -0,0 +1,119 @@ +# chatco-autoreg + +Авторег chat.co + OpenAI-совместимый шлюз на пул аккаунтов. + +Ферма: `farm.py` (один аккаунт) / `farm2.py` (волна с лентами и атомарным резервом почты). +Шлюз: `shim2.py` — `/v1/chat/completions` (+ SSE), `/v1/models`, `/health`, round-robin по аккаунтам с авторефрешем JWT. + +## Что внутри + +``` +farm.py авторег одного аккаунта: email -> Turnstile -> OTP -> verify -> chatbot -> api keys +farm2.py волна: N аккаунтов, K лент, резерв почты через O_CREAT|O_EXCL +shim2.py OpenAI-совместимый шлюз (stdlib http.server, без зависимостей кроме requests) +models.json каталог: display name -> {id, api, credit} (93 модели) +healthcheck.py разовая проверка пула: /health + тестовый чат +``` + +## Как устроен chat.co (реверс) + +Два хоста: + +- `https://fwb567mce3.us-east-1.awsapprunner.com` — dashboard/API аккаунта (auth, chatbot, api-keys) +- `https://api.chat.co` — клиентский API, работает по ключу `sk_live_...` + +Поток регистрации: + +``` +POST /auth/login {email, turnstileToken} -> 200 (письмо с 6-значным кодом) +POST /auth/verify/email {email, otp} -> 200 {data.tokens{accessToken, refreshToken}} +POST /chatbot {name, chatLimit: 2000} -> chatbot.id +POST /api-keys {name, chatbotId, scopes} -> sk_live_... (ключ на бота) +POST /api-keys {name, scopes} -> sk_live_... (ключ аккаунта, для баланса) +``` + +Turnstile: sitekey `0x4AAAAAAChjbcr8LGkrIuGG`, страница `https://chat.co/auth/login`, +решается `TurnstileTaskProxyless` через 2captcha (прокси не нужен). + +Free-план: 2000 кредитов на бота, списание зависит от модели (`credit` в `models.json`, +от 1 у nano до 100+ у флагманов). Смена модели — `PATCH /chatbot/{id}/ai-model {aiModelId}`. + +Чат: + +``` +POST api.chat.co/client/v1/conversations -> conversation.id +POST api.chat.co/client/v1/conversations/{id}/messages {message} -> data.botResponse.content +GET api.chat.co/client/v1/message-allocation -> доступные кредиты по ботам +``` + +Ограничение апстрима: **одно поле `message`** (плюс `documentIds`), истории сообщений нет. +Шлюз склеивает историю в один промпт (`flatten()`), системный промпт уходит блоком `[SYSTEM]`. + +## Шлюз + +```bash +export CHATCO_POOL=/opt/chatco-shim/pool.jsonl +export CHATCO_PORT=8833 +python3 shim2.py +``` + +``` +GET /health -> {ok, accounts, models, credits{email: left}} +GET /v1/models -> список моделей chat.co (api-имена) +POST /v1/chat/completions -> OpenAI-формат, stream=true отдаёт SSE +``` + +Особенности: + +- round-robin (`pick`) — аккаунты выгорают ровно, а не первый до нуля; +- кредиты кэшируются на 120 с (`ALLOC_TTL`), запрашиваются у апстрима по `acct_key`; +- `401` от дашборда -> авторефреш по `refresh_token` и повтор запроса; +- ключ на входе шлюза не проверяется — ставьте перед ним auth-гейт (см. SETUP.md). + +## Почва (email) + +Нужны ящики с рабочим IMAP: код приходит только письмом. В `farm.py` поддерживаются +rambler.ru, gazeta.pl, lenta.ru, ro.ru, i.ua, topnet.tn, singnet.com.sg, rediffmail.com, +mail.tmwlsw.com, tvnetwork.hu, aliyun.com. Формат файла `soil.txt` — `email:password`, по строке. + +`rediffmail.com` пропускается: у них только POP3, IMAP отбивает. + +## Пул + +`pool.jsonl`, по строке на попытку: + +```json +{"email": "...", "ok": true, "bot": "...", "key": "sk_live_...", "acct_key": "sk_live_...", + "at": "eyJ...", "rt": "eyJ...", "ts": 1793698261, "pw": "..."} +``` + +`pool_state.json` — обновлённые `at`/`rt`/`credits` (шлюз пишет сам при рефреше и списании). + +Резерв: `reserved/` создаётся через `O_CREAT|O_EXCL` — два воркера никогда +не возьмут один ящик, даже если запущены одновременно. + +## Цифры (реальный прогон) + +``` +аккаунтов в пуле 542 +моделей 93 +кредитов 288 000+ (по 2000 на бота, часть просажена) +регистрация 1 аккаунт ~ 25-60 с (зависит от письма) +отказы bot 403 (антифрод по IP), verify 400 (OTP), otp (IMAP-троттлинг) +``` + +## Пиитфолы + +1. `POST /auth/login` отдаёт 403 при заходе с «грязного» IP — менять egress, а не почту. +2. OTP живёт минуты: `wait_otp` читает только письма от `chat.co` и только последние 12 писем; + при IMAP-троттлинге повторный опрос каждые 10 с. +3. Один ящик = один аккаунт навсегда: `verify 400 Invalid OTP` после успешного `login` + чаще значит «ящик уже использован», чем «код протух». +4. Кредиты списываются на боте, ключ `acct_key` нужен только для чтения баланса — + без него шлюз считает по локальному счётчику и врёт в плюс. +5. Модель переключается на боте, а не в запросе: шлюз делает `GET /chatbot/{id}` и при + расхождении `PATCH /ai-model`. Параллельные запросы на один аккаунт держит `lock`. + +## Лицензия + +Код публикуется как есть, для тестов на своём железе. Ответственность за использование — на запускающем. \ No newline at end of file diff --git a/SETUP.md b/SETUP.md new file mode 100644 index 0000000..129c897 --- /dev/null +++ b/SETUP.md @@ -0,0 +1,115 @@ +# SETUP + +## 1. Зависимости + +```bash +python3 -m venv venv && . venv/bin/activate +pip install -r requirements.txt +``` + +Нужен Python 3.9+. Шлюз — stdlib, регистрация — `requests`. + +## 2. Переменные окружения + +```bash +cp .env.example .env && . ./env.sh # или экспортируйте вручную +``` + +| Переменная | Назначение | Дефолт | +|---|---|---| +| `CHATCO_CAP` | ключ 2captcha (32 hex) | — | +| `CHATCO_CAP_FILE` | файл с ключом 2captcha | `cap.txt` | +| `CHATCO_SOIL` | пул почты `email:password` | `soil.txt` | +| `CHATCO_POOL` | `pool.jsonl` | рядом со скриптом | +| `CHATCO_STATE` | `pool_state.json` | рядом со скриптом | +| `CHATCO_PORT` | порт шлюза | `8831` | +| `CHATCO_API` | dashboard-хост chat.co | зашит прод | + +## 3. Регистрация + +Один аккаунт: + +```bash +export CHATCO_CAP=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +python3 farm.py 1 +``` + +Волна в 4 ленты по 10 аккаунтов (каждая лента — свой воркер): + +```bash +python3 farm.py 10 0 4 & +python3 farm.py 10 1 4 & +python3 farm.py 10 2 4 & +python3 farm.py 10 3 4 & +``` + +Проверка пула: + +```bash +python3 healthcheck.py # /health + тестовый чат +python3 healthcheck.py --pool pool.jsonl --test claude-opus-5-5 +``` + +## 4. Шлюз + +```bash +export CHATCO_POOL=$PWD/pool.jsonl +export CHATCO_PORT=8833 +python3 shim2.py +``` + +Проверка: + +```bash +curl -s localhost:8833/health | jq +curl -s localhost:8833/v1/chat/completions -H 'content-type: application/json' \ + -d '{"model":"claude-opus-5-5","messages":[{"role":"user","content":"Say OK"}]}' | jq -r '.choices[0].message.content' +``` + +## 5. systemd + +`/etc/systemd/system/chatco-shim.service`: + +```ini +[Unit] +Description=chat.co OpenAI shim +After=network-online.target + +[Service] +Type=simple +WorkingDirectory=/opt/chatco-shim +Environment=CHATCO_POOL=/opt/chatco-shim/pool.jsonl +Environment=CHATCO_PORT=8833 +ExecStart=/usr/bin/python3 /opt/chatco-shim/shim2.py +Restart=always +RestartSec=5 + +[Install] +WantedBy=multi-user.target +``` + +```bash +systemctl daemon-reload && systemctl enable --now chatco-shim && systemctl is-active chatco-shim +``` + +Шлюз слушает `127.0.0.1` — наружу выставляйте через reverse-proxy со своей проверкой ключа. +Пример: Caddy `handle_path /chatco/*` -> `127.0.0.1:8833` плюс auth-гейт перед апстримом. + +## 6. Подключение как провайдера + +Любой OpenAI-совместимый клиент: + +``` +base_url: http://127.0.0.1:8833/v1 +api_key: любой (шлюз не проверяет, гейт — снаружи) +model: claude-opus-5-5 | gpt-6-astra | gemini-4-argon | ... +``` + +Полный список: `curl -s localhost:8833/v1/models | jq -r '.data[].id'`. + +## Порядок действий при сбое + +1. `curl localhost:8833/health` — если `accounts: 0`, пул не загрузился (проверьте `CHATCO_POOL`). +2. Если аккаунты есть, но запросы 502 — смотрите сообщение ошибки: `refresh 401` = JWT мёртв (аккаунт выбыл), `switch 4xx` = модель недоступна на free-плане. +3. `otp` в логах фермы = почтовый сервер троттлит IMAP; подождите и перезапустите ленту, ящик не сгорел. +4. `verify 400` = ящик уже израсходован или код протух; такой ящик помечайте и не берите снова. \ No newline at end of file diff --git a/env.sh b/env.sh new file mode 100644 index 0000000..55bcd5c --- /dev/null +++ b/env.sh @@ -0,0 +1,3 @@ +#!/bin/sh +# экспорт переменных из .env +set -a; [ -f .env ] && . ./.env; set +a diff --git a/farm.py b/farm.py new file mode 100644 index 0000000..6e49676 --- /dev/null +++ b/farm.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +# chat.co autoreg: email -> Turnstile -> OTP -> verify -> bot -> api keys +import json, os, re, sys, time, imaplib, email, random, threading +import requests + +API = os.environ.get('CHATCO_API', 'https://fwb567mce3.us-east-1.awsapprunner.com') +CLIENT = 'https://api.chat.co' +SITE = '0x4AAAAAAChjbcr8LGkrIuGG' +CAP = os.environ.get('CHATCO_CAP') or open(os.environ.get('CHATCO_CAP_FILE', 'cap.txt'), encoding='utf-8').read().strip() +HERE = os.path.dirname(os.path.abspath(__file__)) +UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0 Safari/537.36' +H = {'Content-Type': 'application/json', 'Origin': 'https://chat.co', 'Referer': 'https://chat.co/auth/login', 'User-Agent': UA} +SCOPES = ['chat:read', 'chat:write', 'bot:read', 'bot:write', 'analytics:read', 'content:read', 'content:write', 'crawl:read', 'crawl:write'] + +IMAP = { + 'rambler.ru': ('imap.rambler.ru', 993), + 'gazeta.pl': ('imap.gazeta.pl', 993), + 'lenta.ru': ('imap.lenta.ru', 993), + 'ro.ru': ('imap.ro.ru', 993), + 'i.ua': ('imap.i.ua', 993), + 'topnet.tn': ('imap.topnet.tn', 993), + 'singnet.com.sg': ('imap.singnet.com.sg', 993), + 'rediffmail.com': ('imap.rediffmail.com', 993), + 'mail.tmwlsw.com': ('imap.mail.tmwlsw.com', 993), + 'tvnetwork.hu': ('imap.tvnetwork.hu', 993), + 'aliyun.com': ('imap.aliyun.com', 993), +} + + +def log(*a): + print(time.strftime('%H:%M:%S'), *a, flush=True) + + +def ts_token(page='https://chat.co/auth/login', tries=2): + for _ in range(tries): + r = requests.post('https://api.2captcha.com/createTask', json={'clientKey': CAP, 'task': {'type': 'TurnstileTaskProxyless', 'websiteURL': page, 'websiteKey': SITE}}, timeout=40).json() + if 'taskId' not in r: + log('createTask err', str(r)[:120]); continue + tid = r['taskId']; t0 = time.time() + while time.time() - t0 < 200: + time.sleep(4) + g = requests.post('https://api.2captcha.com/getTaskResult', json={'clientKey': CAP, 'taskId': tid}, timeout=40).json() + if g.get('status') == 'ready': + return g['solution']['token'] + raise RuntimeError('no turnstile token') + + +def wait_otp(mail, pw, t0, timeout=300): + dom = mail.split('@')[1].lower() + host, port = IMAP.get(dom, ('imap.' + dom, 993)) + deadline = time.time() + timeout + while time.time() < deadline: + try: + M = imaplib.IMAP4_SSL(host, port, timeout=25) + M.login(mail, pw); M.select('INBOX', readonly=True) + typ, d = M.search(None, 'ALL'); ids = d[0].split() if d and d[0] else [] + for i in reversed(ids[-12:]): + t, dd = M.fetch(i, '(RFC822)'); m = email.message_from_bytes(dd[0][1]) + if 'chat.co' not in (m['From'] or '').lower(): + continue + body = '' + for p in m.walk(): + if p.get_content_type() == 'text/html': + body = p.get_payload(decode=True).decode('utf-8', 'ignore'); break + if not body: + for p in m.walk(): + if p.get_content_type() == 'text/plain': + body = p.get_payload(decode=True).decode('utf-8', 'ignore'); break + txt = re.sub(r'', ' ', body) + txt = re.sub(r'<[^>]+>', ' ', txt); txt = re.sub(r'\s+', ' ', txt) + mm = re.search(r'verification code\s*(\d{6})', txt, re.I) or re.search(r'\b(\d{6})\b', txt) + if mm: + M.logout(); return mm.group(1) + M.logout() + except Exception as e: + log('imap', dom, type(e).__name__, str(e)[:60]) + time.sleep(10) + return None + + +def reg_one(mail, pw): + t0 = time.time() + tok = ts_token() + s = requests.Session() + r = s.post(API + '/auth/login', json={'email': mail, 'turnstileToken': tok}, headers=H, timeout=60) + if r.status_code not in (200, 201): + return {'email': mail, 'ok': False, 'stage': 'login', 'code': r.status_code, 'body': r.text[:160]} + otp = wait_otp(mail, pw, t0) + if not otp: + return {'email': mail, 'ok': False, 'stage': 'otp'} + r = s.post(API + '/auth/verify/email', json={'email': mail, 'otp': otp}, headers=H, timeout=60) + if r.status_code not in (200, 201): + return {'email': mail, 'ok': False, 'stage': 'verify', 'code': r.status_code, 'body': r.text[:160]} + tokens = r.json()['data']['tokens'] + AH = {'Authorization': 'Bearer ' + tokens['accessToken'], 'Content-Type': 'application/json', 'Origin': 'https://chat.co', 'User-Agent': UA} + # бот + rr = s.post(API + '/chatbot', json={'name': 'node', 'chatLimit': 2000}, headers=AH, timeout=60) + if rr.status_code not in (200, 201): + return {'email': mail, 'ok': False, 'stage': 'bot', 'code': rr.status_code, 'body': rr.text[:160]} + bot = rr.json()['data']['chatbot']['id'] + rr = s.post(API + '/api-keys', json={'name': 'full', 'chatbotId': bot, 'scopes': SCOPES}, headers=AH, timeout=60) + key = rr.json()['data']['key'] + rr = s.post(API + '/api-keys', json={'name': 'acct', 'scopes': SCOPES}, headers=AH, timeout=60) + akey = rr.json()['data']['key'] + return {'email': mail, 'ok': True, 'bot': bot, 'key': key, 'acct_key': akey, + 'at': tokens['accessToken'], 'rt': tokens['refreshToken'], 'ts': int(time.time())} + + +def mails(n, seen): + out = [] + for line in open(os.environ.get('CHATCO_SOIL','soil.txt'), encoding='utf-8', errors='ignore'): + line = line.strip() + if not line or ':' not in line: + continue + m, p = line.rsplit(':', 1) + dom = m.split('@')[-1].lower() + if dom not in IMAP or m in seen: + continue + if dom == 'rediffmail.com': # POP3-only, IMAP отбивает + continue + out.append((m, p)); seen.add(m) + if len(out) >= n: + break + return out + + +if __name__ == '__main__': + n = int(sys.argv[1]) if len(sys.argv) > 1 else 3 + pool = os.environ.get('CHATCO_POOL', os.path.join(HERE, 'pool.jsonl')) + seen = set() + if os.path.exists(pool): + for line in open(pool, encoding='utf-8'): + try: seen.add(json.loads(line)['email']) + except Exception: pass + todo = mails(n * 3, seen) + ok = 0 + for m, p in todo: + if ok >= n: + break + try: + res = reg_one(m, p); res['pw'] = p + except Exception as e: + res = {'email': m, 'ok': False, 'stage': 'exc', 'body': str(e)[:160]} + with open(pool, 'a', encoding='utf-8') as f: + f.write(json.dumps(res, ensure_ascii=False) + '\n') + log(('OK ' if res.get('ok') else 'FAIL ') + m, res.get('stage', ''), res.get('code', '')) + if res.get('ok'): + ok += 1 + time.sleep(3) + log('done ok=%d' % ok) \ No newline at end of file diff --git a/farm2.py b/farm2.py new file mode 100644 index 0000000..fc2c0d7 --- /dev/null +++ b/farm2.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +# chat.co авторег, ленты: farm2.py +import json, os, re, sys, time, imaplib, email, hashlib +import requests + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from farm import API, CLIENT, H, SCOPES, UA, ts_token, wait_otp, reg_one, IMAP # noqa + +HERE = os.path.dirname(os.path.abspath(__file__)) +POOL = os.path.join(HERE, 'pool.jsonl') +USED = os.path.join(HERE, 'used_emails.txt') +RES = os.path.join(HERE, 'reserved') +MAILFILE = 'C:/Users/User/tmp/mail66k/LIVE/live_all.txt' +os.makedirs(RES, exist_ok=True) + + +def log(*a): + print(time.strftime('%H:%M:%S'), *a, flush=True) + + +def claim(m): + key = hashlib.sha1(m.lower().strip().encode()).hexdigest()[:20] + try: + fd = os.open(os.path.join(RES, key), os.O_CREAT | os.O_EXCL | os.O_WRONLY) + os.write(fd, m.encode()) + os.close(fd) + return True + except FileExistsError: + return False + + +def load_used(): + s = set() + if os.path.exists(USED): + for l in open(USED, encoding='utf-8', errors='ignore'): + l = l.strip() + if l: s.add(l) + if os.path.exists(POOL): + for l in open(POOL, encoding='utf-8'): + try: s.add(json.loads(l)['email']) + except Exception: pass + if os.path.isdir(RES): + for f in os.listdir(RES): + try: + v = open(os.path.join(RES, f), encoding='utf-8', errors='ignore').read().strip() + if v: s.add(v) + except Exception: + pass + return s + + +def main(): + n = int(sys.argv[1]); lane = int(sys.argv[2]); lanes = int(sys.argv[3]) + used = load_used() + cand = [] + idx = -1 + for line in open(MAILFILE, encoding='utf-8', errors='ignore'): + line = line.strip() + if not line or ':' not in line: continue + m, p = line.rsplit(':', 1) + dom = m.split('@')[-1].lower() + if dom not in IMAP or dom == 'rediffmail.com': continue + idx += 1 + if idx % lanes != lane: continue + if m in used: continue + cand.append((m, p)) + if len(cand) >= n * 4: break + log('lane %d/%d candidates %d' % (lane, lanes, len(cand))) + ok = 0 + for m, p in cand: + if ok >= n: break + if not claim(m): + log('SKIP ' + m + ' (reserved by other lane)') + continue + try: + res = reg_one(m, p); res['pw'] = p + except Exception as e: + res = {'email': m, 'ok': False, 'stage': 'exc', 'body': str(e)[:160]} + with open(POOL, 'a', encoding='utf-8') as f: + f.write(json.dumps(res, ensure_ascii=False) + '\n') + with open(USED, 'a', encoding='utf-8') as f: + f.write(m + '\n') + log(('OK ' if res.get('ok') else 'FAIL ') + m + ' ' + str(res.get('stage', '')) + ' ' + str(res.get('code', ''))) + if res.get('ok'): ok += 1 + time.sleep(2) + log('lane %d done ok=%d' % (lane, ok)) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/healthcheck.py b/healthcheck.py new file mode 100644 index 0000000..e2638f1 --- /dev/null +++ b/healthcheck.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""healthcheck.py — проверка пула chat.co и шлюза. + + python3 healthcheck.py # health локального шлюза + python3 healthcheck.py --pool pool.jsonl # сколько живых аккаунтов в пуле + python3 healthcheck.py --test claude-opus-5-5 # тестовый чат через шлюз +""" +import argparse, json, os, sys, time, urllib.request, urllib.error + +def get(url, timeout=30): + with urllib.request.urlopen(url, timeout=timeout) as r: + return json.loads(r.read().decode()) + +def post(url, body, timeout=180): + req = urllib.request.Request(url, data=json.dumps(body).encode(), + headers={"content-type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return r.status, json.loads(r.read().decode()) + except urllib.error.HTTPError as e: + return e.code, e.read().decode()[:300] + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base", default="http://127.0.0.1:8833") + ap.add_argument("--pool", default=os.environ.get("CHATCO_POOL", "pool.jsonl")) + ap.add_argument("--test", default="") + a = ap.parse_args() + + if os.path.exists(a.pool): + ok = bad = 0 + for line in open(a.pool, encoding="utf-8"): + line = line.strip() + if not line: + continue + try: + r = json.loads(line) + except Exception: + continue + ok += 1 if r.get("ok") else 0 + bad += 0 if r.get("ok") else 1 + print("pool: %s | ok=%d fail=%d" % (a.pool, ok, bad)) + else: + print("pool: %s не найден" % a.pool) + + try: + h = get(a.base + "/health") + print("health: accounts=%s models=%s" % (h.get("accounts"), h.get("models"))) + credits = h.get("credits") or {} + if credits: + top = sorted(credits.items(), key=lambda kv: -float(kv[1]))[:3] + print("top credits:", ", ".join("%s=%.0f" % (k.split("@")[0], float(v)) for k, v in top)) + except Exception as e: + print("health: FAIL %s" % e) + return 1 + + if a.test: + t0 = time.time() + code, body = post(a.base + "/v1/chat/completions", + {"model": a.test, "max_tokens": 30, + "messages": [{"role": "user", "content": "Say OK"}]}) + if code == 200 and isinstance(body, dict): + txt = (body.get("choices") or [{}])[0].get("message", {}).get("content", "") + print("test %-18s 200 %.1fs | %s" % (a.test, time.time() - t0, " ".join(txt.split())[:60])) + else: + print("test %-18s %s %s" % (a.test, code, str(body)[:160])) + return 1 + return 0 + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/models.json b/models.json new file mode 100644 index 0000000..4a612d3 --- /dev/null +++ b/models.json @@ -0,0 +1,467 @@ +{ + "GPT-5 Mini": { + "id": "6948a9b8348be275bb55551a", + "api": "gpt-5-mini", + "credit": 2.5 + }, + "GPT-4.1 Mini": { + "id": "6948a9b8348be275bb55551b", + "api": "gpt-4.1-mini", + "credit": 5 + }, + "GPT-5 Nano": { + "id": "6948a9b8348be275bb55551d", + "api": "gpt-5-nano", + "credit": 1 + }, + "GPT-4.1 Nano": { + "id": "6948a9b8348be275bb55551e", + "api": "gpt-4.1-nano", + "credit": 1 + }, + "Grok-4.1 Fast (Non-Reasoning)": { + "id": "6948a9b8348be275bb55552b", + "api": "grok-4-1-fast-non-reasoning", + "credit": 1.5 + }, + "Gemini 2.5 Flash": { + "id": "6948a9b8348be275bb555530", + "api": "gemini-2.5-flash", + "credit": 2.5 + }, + "Gemma 3 4B (Bedrock)": { + "id": "6948a9b8348be275bb55553f", + "api": "google.gemma-3-4b-it", + "credit": 1 + }, + "Gemma 3 12B (Bedrock)": { + "id": "6948a9b8348be275bb555540", + "api": "google.gemma-3-12b-it", + "credit": 1 + }, + "Qwen3 32B (Dense) (Bedrock)": { + "id": "6948a9b8348be275bb555541", + "api": "qwen.qwen3-32b-v1:0", + "credit": 1 + }, + "GPT-6 Sol": { + "id": "6ab2e59e73a4aa4e62c416d9", + "api": "gpt-6-sol", + "credit": 4 + }, + "GPT-6 Luna": { + "id": "6ab2e59e73a4aa4e62c416da", + "api": "gpt-6-luna", + "credit": 1 + }, + "GPT-4.1": { + "id": "68adce5ec3b6f715d966c7a4", + "api": "gpt-4.1", + "credit": 5 + }, + "Claude Opus 4.1": { + "id": "68c9990ec35ba9c1e4c381bd", + "api": "claude-opus-4-1", + "credit": 10 + }, + "Claude Sonnet 4": { + "id": "68c9990ec35ba9c1e4c381be", + "api": "claude-sonnet-4", + "credit": 7 + }, + "GPT-4o": { + "id": "68c9990ec35ba9c1e4c381c4", + "api": "gpt-4o", + "credit": 6 + }, + "GPT-5.1": { + "id": "6948a9b8348be275bb555513", + "api": "gpt-5.1", + "credit": 5 + }, + "GPT-5": { + "id": "6948a9b8348be275bb555514", + "api": "gpt-5", + "credit": 5 + }, + "GPT-5.1 Chat (Latest)": { + "id": "6948a9b8348be275bb555515", + "api": "gpt-5.1-chat-latest", + "credit": 5 + }, + "GPT-4o (2024-05-13)": { + "id": "6948a9b8348be275bb555518", + "api": "gpt-4o-2024-05-13", + "credit": 8 + }, + "GPT-4o Mini": { + "id": "6948a9b8348be275bb55551c", + "api": "gpt-4o-mini", + "credit": 1.5 + }, + "Claude Opus 4.5": { + "id": "6948a9b8348be275bb55551f", + "api": "claude-opus-4-5", + "credit": 9 + }, + "Claude Opus 4": { + "id": "6948a9b8348be275bb555520", + "api": "claude-opus-4", + "credit": 10 + }, + "Claude Sonnet 4.5": { + "id": "6948a9b8348be275bb555521", + "api": "claude-sonnet-4-5", + "credit": 1 + }, + "Claude Haiku 4.5": { + "id": "6948a9b8348be275bb555522", + "api": "claude-haiku-4-5", + "credit": 4 + }, + "Grok-4 (0709)": { + "id": "6948a9b8348be275bb555527", + "api": "grok-4-0709", + "credit": 7 + }, + "Grok-3": { + "id": "6948a9b8348be275bb555528", + "api": "grok-3", + "credit": 7 + }, + "Grok-4.1 Fast (Reasoning)": { + "id": "6948a9b8348be275bb555529", + "api": "grok-4-1-fast-reasoning", + "credit": 1.5 + }, + "Grok-4 Fast (Reasoning)": { + "id": "6948a9b8348be275bb55552a", + "api": "grok-4-fast-reasoning", + "credit": 1.5 + }, + "Grok-4 Fast (Non-Reasoning)": { + "id": "6948a9b8348be275bb55552c", + "api": "grok-4-fast-non-reasoning", + "credit": 1.5 + }, + "Grok-3 Mini": { + "id": "6948a9b8348be275bb55552d", + "api": "grok-3-mini", + "credit": 1.5 + }, + "Grok Code Fast": { + "id": "6948a9b8348be275bb55552e", + "api": "grok-code-fast-1", + "credit": 2.5 + }, + "Gemini 2.5 Pro": { + "id": "6948a9b8348be275bb55552f", + "api": "gemini-2.5-pro", + "credit": 5 + }, + "Gemini 2.0 Flash": { + "id": "6948a9b8348be275bb555531", + "api": "gemini-2.0-flash", + "credit": 1 + }, + "Gemini 2.5 Flash-Lite": { + "id": "6948a9b8348be275bb555532", + "api": "gemini-2.5-flash-lite", + "credit": 1 + }, + "Gemini 2.0 Flash-Lite": { + "id": "6948a9b8348be275bb555533", + "api": "gemini-2.0-flash-lite", + "credit": 1 + }, + "Llama 4 Maverick (Bedrock)": { + "id": "6948a9b8348be275bb555534", + "api": "meta.llama4-maverick-17b-instruct-v1:0", + "credit": 2 + }, + "Llama 3.3 70B Instruct (Bedrock)": { + "id": "6948a9b8348be275bb555535", + "api": "meta.llama3-3-70b-instruct-v1:0", + "credit": 3.5 + }, + "Llama 3.1 70B Instruct (Bedrock)": { + "id": "6948a9b8348be275bb555536", + "api": "meta.llama3-1-70b-instruct-v1:0", + "credit": 3.5 + }, + "Llama 3 70B Instruct (Bedrock)": { + "id": "6948a9b8348be275bb555537", + "api": "meta.llama3-1-70b-instruct-v1:0", + "credit": 3.5 + }, + "Llama 4 Scout (Bedrock)": { + "id": "6948a9b8348be275bb555538", + "api": "meta.llama4-scout-17b-instruct-v1:0", + "credit": 1.5 + }, + "Llama 3.1 8B Instruct (Bedrock)": { + "id": "6948a9b8348be275bb555539", + "api": "meta.llama3-1-8b-instruct-v1:0", + "credit": 1 + }, + "Llama 3 8B Instruct (Bedrock)": { + "id": "6948a9b8348be275bb55553a", + "api": "meta.llama3-1-8b-instruct-v1:0", + "credit": 1 + }, + "Llama 3.2 3B Instruct (Bedrock)": { + "id": "6948a9b8348be275bb55553b", + "api": "meta.llama3-2-3b-instruct-v1:0", + "credit": 1 + }, + "DeepSeek-R1 (Bedrock)": { + "id": "6948a9b8348be275bb55553c", + "api": "deepseek.r1-v1:0", + "credit": 4 + }, + "Mistral Small (24.02)": { + "id": "6948a9b8348be275bb55553d", + "api": "mistral.mistral-small-2402-v1:0", + "credit": 1 + }, + "Mistral Large (24.02)": { + "id": "6948a9b8348be275bb55553e", + "api": "mistral.mistral-large-2402-v1:0", + "credit": 2.5 + }, + "Claude Opus 4.6": { + "id": "6986a27763076b67fd535c3e", + "api": "claude-opus-4-6", + "credit": 9 + }, + "Claude Sonnet 4.6": { + "id": "69976aa04e380653d68f18a1", + "api": "claude-sonnet-4-6", + "credit": 7 + }, + "Gemini 3.1 Pro": { + "id": "69976aa04e380653d68f18a2", + "api": "gemini-3.1-pro-preview", + "credit": 8 + }, + "GPT-5.3": { + "id": "69a749093ce37e00bbda9746", + "api": "gpt-5.3-chat-latest", + "credit": 7 + }, + "Gemini 3.1 Flash-Lite": { + "id": "69a8a32bcb8759bffd0efd37", + "api": "gemini-3.1-flash-lite-preview", + "credit": 1 + }, + "GPT-5.4": { + "id": "69a9d6cba81307780016cef6", + "api": "gpt-5.4", + "credit": 8 + }, + "GPT-5.4 Pro": { + "id": "69a9d6cba81307780016cef7", + "api": "gpt-5.4-pro", + "credit": 12 + }, + "Gemma 4 31B Dense": { + "id": "69d0a469481d4d782a54e66e", + "api": "gemma-4-31b-it", + "credit": 3 + }, + "Gemma 4 26B (MoE)": { + "id": "69d0a469481d4d782a54e66f", + "api": "gemma-4-26b-a4b-it", + "credit": 2 + }, + "Claude Opus 4.7": { + "id": "69e14b0834f506179b3754ee", + "api": "claude-opus-4-7", + "credit": 10 + }, + "GPT-5.5": { + "id": "69eebf9870a4aa99165f0883", + "api": "gpt-5.5", + "credit": 10 + }, + "Gemini 3.5 Flash": { + "id": "6a0f517e633ca9a88aeec348", + "api": "gemini-3.5-flash", + "credit": 7 + }, + "Claude Opus 4.8": { + "id": "6a1901f9751846ea4278555f", + "api": "claude-opus-4-8", + "credit": 10 + }, + "Claude Opus 4.8 (Bedrock)": { + "id": "6a19b5aa5d8452dbcbaf1556", + "api": "anthropic.claude-opus-4-8", + "credit": 10 + }, + "Claude Opus 4.7 (Bedrock)": { + "id": "6a19b5aa5d8452dbcbaf1557", + "api": "anthropic.claude-opus-4-7", + "credit": 10 + }, + "Claude Opus 4.6 (Bedrock)": { + "id": "6a19b5aa5d8452dbcbaf1558", + "api": "anthropic.claude-opus-4-6-v1", + "credit": 9 + }, + "Claude Opus 4.5 (Bedrock)": { + "id": "6a19b5aa5d8452dbcbaf1559", + "api": "anthropic.claude-opus-4-5-20251101-v1:0", + "credit": 9 + }, + "Kimi K2.5 (Bedrock)": { + "id": "6a28880701aa87b83e97323d", + "api": "moonshotai.kimi-k2.5", + "credit": 4 + }, + "Claude Fable 5": { + "id": "6a28b0f7eb87df04ca6a900e", + "api": "claude-fable-5", + "credit": 20 + }, + "Claude Fable 5 (Bedrock)": { + "id": "6a28b0f7eb87df04ca6a900f", + "api": "anthropic.claude-fable-5", + "credit": 20 + }, + "Grok 4.3 (Bedrock)": { + "id": "6a39e47efd7aec21d644b7cc", + "api": "xai.grok-4.3", + "credit": 4 + }, + "Claude Sonnet 5": { + "id": "6a445e8aa01b4a988a3ce907", + "api": "claude-sonnet-5", + "credit": 7 + }, + "Claude Sonnet 5 (Bedrock)": { + "id": "6a467101f904ef77db47ba12", + "api": "anthropic.claude-sonnet-5", + "credit": 7 + }, + "GPT-5.6 Sol": { + "id": "6a545b3032fe790c2723ee88", + "api": "gpt-5.6-sol", + "credit": 10 + }, + "GPT-5.6 Terra": { + "id": "6a545b3032fe790c2723ee89", + "api": "gpt-5.6-terra", + "credit": 6 + }, + "GPT-5.6 Luna": { + "id": "6a545b3032fe790c2723ee8a", + "api": "gpt-5.6-luna", + "credit": 3 + }, + "Claude Opus 5": { + "id": "6a63b7f21f8193b0f4611c0d", + "api": "claude-opus-5", + "credit": 10 + }, + "Claude Opus 5 (Bedrock)": { + "id": "6a63b7f21f8193b0f4611c0e", + "api": "anthropic.claude-opus-5", + "credit": 10 + }, + "Gemini 3.6 Flash": { + "id": "6a65523814584f46153ae955", + "api": "gemini-3.6-flash", + "credit": 7 + }, + "Gemini 3.5 Flash-Lite": { + "id": "6a65523814584f46153ae956", + "api": "gemini-3.5-flash-lite", + "credit": 2 + }, + "Grok 4.6": { + "id": "6a7cfa1e11b3b38ab1c318ae", + "api": "grok-4.6", + "credit": 4 + }, + "Gemini 3.7 Flash": { + "id": "6a7eae69926b3a757561bfd4", + "api": "gemini-3.7-flash", + "credit": 7 + }, + "Grok 4.6 (Bedrock)": { + "id": "6a87db6aa7ac645ab541b529", + "api": "global.xai.grok-4.6", + "credit": 5 + }, + "Claude Fable 5.1": { + "id": "6a972ed0ae488f68b8b263ae", + "api": "claude-fable-5-1", + "credit": 20 + }, + "Claude Fable 5.1 (Bedrock)": { + "id": "6a972ed0ae488f68b8b263af", + "api": "anthropic.claude-fable-5-1", + "credit": 20 + }, + "GPT-6 Astra": { + "id": "6a9f9f4c1df2c25566a61894", + "api": "gpt-6-astra", + "credit": 20 + }, + "Claude Opus 5.5": { + "id": "6ab2ca5f5e2524e238668e4f", + "api": "claude-opus-5-5", + "credit": 8 + }, + "Grok 4.3 (Fast)": { + "id": "6ab600e25dc8cc609e69da54", + "api": "grok-4.3", + "credit": 1.5 + }, + "Claude Opus 5.5 (Bedrock)": { + "id": "6abab0e83ed6c31e8192c909", + "api": "global.anthropic.claude-opus-5-5", + "credit": 8 + }, + "Claude Sonnet 5.5 (Bedrock)": { + "id": "6abab3205ab7029988c1dc39", + "api": "global.anthropic.claude-sonnet-5-5", + "credit": 7 + }, + "GPT-6.1 Sol": { + "id": "6abc2db38bb837554a4cb47a", + "api": "gpt-6.1-sol", + "credit": 4 + }, + "Claude Sonnet 5.5": { + "id": "6abc2db38bb837554a4cb47b", + "api": "claude-sonnet-5-5", + "credit": 7 + }, + "Grok 4.7": { + "id": "6ab19143db2c075ea10a43ba", + "api": "grok-4.7", + "credit": 4 + }, + "Claude Haiku 5.5": { + "id": "6ac6978c6d8f34d44682762d", + "api": "claude-haiku-5-5", + "credit": 1 + }, + "Claude Haiku 5.5 (Bedrock)": { + "id": "6ac6978c6d8f34d44682762e", + "api": "global.anthropic.claude-haiku-5-5", + "credit": 1 + }, + "Gemini 4 Argon": { + "id": "6acef617efd731cc0da8402f", + "api": "gemini-4-argon", + "credit": 8 + }, + "GPT-6.1 Terra": { + "id": "6adfb65d795133f6ecd813e7", + "api": "gpt-6.1-terra", + "credit": 2 + } +} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..0eb8cae --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +requests>=2.31.0 diff --git a/shim2.py b/shim2.py new file mode 100644 index 0000000..3b0cded --- /dev/null +++ b/shim2.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +# chat.co -> OpenAI-compatible shim, пул аккаунтов (pool.jsonl) +import json, os, sys, time, threading, uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import requests + +HERE = os.path.dirname(os.path.abspath(__file__)) +CLIENT = 'https://api.chat.co' +DASH = 'https://fwb567mce3.us-east-1.awsapprunner.com' +UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0 Safari/537.36' +MODELS = json.load(open(os.path.join(HERE, 'models.json'), encoding='utf-8')) +BY_API = {m['api'].lower(): (n, m) for n, m in MODELS.items()} +POOL_PATH = os.environ.get('CHATCO_POOL') or os.path.join(HERE, 'pool.jsonl') +STATE_PATH = os.environ.get('CHATCO_STATE') or os.path.join(HERE, 'pool_state.json') + +ACCTS = [] # [{email,bot,key,acct_key,at,rt,credits,ts,lock}] +ALLOC_TTL = 120 + + +def log(*a): + print(time.strftime('%H:%M:%S'), *a, flush=True) + + +def load_pool(): + global ACCTS + rows = [] + if os.path.exists(POOL_PATH): + for line in open(POOL_PATH, encoding='utf-8'): + line = line.strip() + if not line: + continue + try: r = json.loads(line) + except Exception: continue + if r.get('ok'): rows.append(r) + st = {} + if os.path.exists(STATE_PATH): + try: st = json.load(open(STATE_PATH, encoding='utf-8')) + except Exception: st = {} + ACCTS = [] + for r in rows: + s = st.get(r['email'], {}) + ACCTS.append({'email': r['email'], 'bot': r['bot'], 'key': r['key'], 'acct_key': r.get('acct_key'), + 'at': s.get('at') or r['at'], 'rt': s.get('rt') or r['rt'], + 'credits': r.get('credits', 2000), 'checked': 0, 'lock': threading.Lock(), 'dead': False}) + log('pool loaded: %d accounts' % len(ACCTS)) + + +def save_state(): + st = {a['email']: {'at': a['at'], 'rt': a['rt'], 'credits': a['credits']} for a in ACCTS} + json.dump(st, open(STATE_PATH, 'w', encoding='utf-8')) + + +def refresh(a): + r = requests.get(DASH + '/auth/refresh', headers={'Authorization': 'Bearer ' + a['rt'], 'Accept': 'application/json', 'User-Agent': UA}, timeout=60) + if r.status_code != 200: + a['dead'] = True + raise RuntimeError('refresh %s %s' % (r.status_code, r.text[:120])) + t = r.json()['data']['tokens']; a['at'], a['rt'] = t['accessToken'], t['refreshToken']; save_state() + + +def dash(a, method, path, body=None): + for attempt in (1, 2): + h = {'Authorization': 'Bearer ' + a['at'], 'Content-Type': 'application/json', 'Origin': 'https://chat.co', 'User-Agent': UA} + r = requests.request(method, DASH + path, headers=h, json=body, timeout=60) + if r.status_code == 401 and attempt == 1: + refresh(a); continue + return r + return r + + +def client(a, method, path, body=None, timeout=300): + h = {'Authorization': 'Bearer ' + a['key'], 'Content-Type': 'application/json', 'User-Agent': UA} + return requests.request(method, CLIENT + path, headers=h, json=body, timeout=timeout) + + +def credits(a): + if not a.get('acct_key'): + return a['credits'] + try: + r = requests.get(CLIENT + '/client/v1/message-allocation', headers={'Authorization': 'Bearer ' + a['acct_key'], 'User-Agent': UA}, timeout=45) + if r.status_code == 200: + for b in r.json()['data'].get('bots', []): + if b['id'] == a['bot']: + a['credits'] = b['available'] + 2000 - 2000 # доступно на боте + a['credits'] = b['available'] + break + a['checked'] = time.time() + except Exception as e: + log('credits', a['email'], type(e).__name__) + return a['credits'] + + +RR = [0] + + +def pick(cost): + """Round-robin по аккаунтам: выгорают равномерно, а не первый до нуля.""" + now = time.time() + n = len(ACCTS) + if not n: + return None + start = RR[0] % n + for i in range(n): + a = ACCTS[(start + i) % n] + if a['dead']: + continue + if now - a.get('checked', 0) > ALLOC_TTL: + credits(a) + if a['credits'] > cost: + RR[0] = (start + i + 1) % n + return a + for i in range(n): + a = ACCTS[(start + i) % n] + if not a['dead']: + RR[0] = (start + i + 1) % n + return a + return None + + +def resolve_model(name): + n = str(name or '').strip().lower() + for pre in ('chat.co/', 'chatco/', 'openai/', 'anthropic/', 'google/'): + if n.startswith(pre): + n = n[len(pre):] + if n in BY_API: + return BY_API[n] + for api, v in BY_API.items(): + if n in api or api in n: + return v + for disp, m in MODELS.items(): + if n == disp.lower(): + return disp, m + return None, None + + +def flatten(messages): + system, parts = None, [] + for m in messages or []: + role = m.get('role'); c = m.get('content') + if isinstance(c, list): + c = ' '.join(x.get('text', '') for x in c if isinstance(x, dict)) + c = c or '' + if role == 'system': + system = (system + '\n' + c) if system else c + elif role == 'assistant': + parts.append('Assistant: ' + c) + else: + parts.append(c if len(messages) == 1 else 'User: ' + c) + return system, ('\n\n'.join(parts) if len(parts) > 1 else (parts[0] if parts else '')) + + +def ask(model_name, prompt, system=None, timeout=300): + disp, m = resolve_model(model_name) + if not m: + raise ValueError('unknown model: %s' % model_name) + a = pick(float(m.get('credit') or 5)) + if not a: + raise RuntimeError('no accounts left') + with a['lock']: + cur = dash(a, 'GET', '/chatbot/' + a['bot']) + if cur.status_code != 200: + raise RuntimeError('bot get %s' % cur.status_code) + if cur.json()['data']['chatbot'].get('aiModelId') != m['id']: + r = dash(a, 'PATCH', '/chatbot/%s/ai-model' % a['bot'], {'aiModelId': m['id']}) + if r.status_code != 200: + raise RuntimeError('switch %s %s' % (r.status_code, r.text[:160])) + r = client(a, 'POST', '/client/v1/conversations', {'metadata': {'source': 'shim'}}) + if r.status_code not in (200, 201): + raise RuntimeError('conv %s %s' % (r.status_code, r.text[:160])) + cid = r.json()['data']['conversation']['id'] + msg = ('[SYSTEM]\n%s\n\n[USER]\n%s' % (system, prompt)) if system else prompt + rr = client(a, 'POST', '/client/v1/conversations/%s/messages' % cid, {'message': msg[:8000]}, timeout=timeout) + if rr.status_code not in (200, 201): + raise RuntimeError('msg %s %s' % (rr.status_code, rr.text[:200])) + txt = rr.json()['data']['botResponse']['content'] + a['credits'] -= float(m.get('credit') or 5) + return txt, disp, cid, a['email'] + + +class H(BaseHTTPRequestHandler): + protocol_version = 'HTTP/1.1' + + def log_message(self, *a): pass + + def sendj(self, code, obj): + b = json.dumps(obj, ensure_ascii=False).encode() + self.send_response(code); self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(b))); self.end_headers(); self.wfile.write(b) + + def do_GET(self): + p = self.path.rstrip('/') + if p in ('/v1/models', '/models'): + now = int(time.time()) + return self.sendj(200, {'object': 'list', 'data': [{'id': m['api'], 'object': 'model', 'created': now, 'owned_by': 'chat.co', 'x_display_name': n, 'x_credit': m.get('credit')} for n, m in MODELS.items()]}) + if p in ('/health', ''): + return self.sendj(200, {'ok': True, 'accounts': len([a for a in ACCTS if not a['dead']]), 'models': len(MODELS), + 'credits': {a['email']: round(a['credits'], 1) for a in ACCTS}}) + self.sendj(404, {'error': {'message': 'not found', 'type': 'not_found'}}) + + def do_POST(self): + if self.path.rstrip('/') not in ('/v1/chat/completions', '/chat/completions'): + return self.sendj(404, {'error': {'message': 'not found'}}) + try: + n = int(self.headers.get('Content-Length') or 0) + req = json.loads(self.rfile.read(n) or b'{}') + except Exception as e: + return self.sendj(400, {'error': {'message': 'bad json %s' % e}}) + system, prompt = flatten(req.get('messages')) + try: + text, disp, cid, acc = ask(req.get('model') or '', prompt, system) + except Exception as e: + return self.sendj(502, {'error': {'message': str(e), 'type': 'upstream_error'}}) + mid = 'chatcmpl-' + uuid.uuid4().hex[:24]; created = int(time.time()) + if not req.get('stream'): + return self.sendj(200, {'id': mid, 'object': 'chat.completion', 'created': created, 'model': disp, + 'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': text}, 'finish_reason': 'stop'}], + 'usage': {'prompt_tokens': len(prompt) // 4, 'completion_tokens': len(text) // 4, 'total_tokens': (len(prompt) + len(text)) // 4}, + 'x_chatco_account': acc}) + self.send_response(200); self.send_header('Content-Type', 'text/event-stream') + self.send_header('Cache-Control', 'no-cache'); self.send_header('Connection', 'keep-alive'); self.end_headers() + + def ch(delta, fin=None): + self.wfile.write(('data: ' + json.dumps({'id': mid, 'object': 'chat.completion.chunk', 'created': created, 'model': disp, + 'choices': [{'index': 0, 'delta': delta, 'finish_reason': fin}]}, ensure_ascii=False) + '\n\n').encode()) + self.wfile.flush() + ch({'role': 'assistant', 'content': ''}) + step = max(1, len(text) // 40) if text else 1 + for i in range(0, len(text), step): + ch({'content': text[i:i + step]}) + ch({}, 'stop'); self.wfile.write(b'data: [DONE]\n\n'); self.wfile.flush() + + +if __name__ == '__main__': + load_pool() + port = int(sys.argv[1]) if len(sys.argv) > 1 else int(os.environ.get('CHATCO_PORT', '8831')) + log('chatco pool shim :%d accounts=%d models=%d' % (port, len(ACCTS), len(MODELS))) + if not ACCTS: + log('WARN: pool пуст') + ThreadingHTTPServer(('127.0.0.1', port), H).serve_forever() \ No newline at end of file