From afab524bb9627c6f6915f0cacb6dab64ed9e7323 Mon Sep 17 00:00:00 2001 From: reform Date: Tue, 3 Nov 2026 18:55:39 +0300 Subject: [PATCH] shim3: native tools, tool_result, SSE tool_calls; anthropic bridge; docs/compat.md --- README.md | 16 +- anth_bridge.py | 411 +++++++++++++++++++++++++++ docs/compat.md | 93 +++++++ shim3.py | 732 +++++++++++++++++++++++++++++++++++++++++++++++++ tests_shim3.py | 66 +++++ 5 files changed, 1315 insertions(+), 3 deletions(-) create mode 100644 anth_bridge.py create mode 100644 docs/compat.md create mode 100644 shim3.py create mode 100644 tests_shim3.py diff --git a/README.md b/README.md index 63851b0..2c9c4a4 100644 --- a/README.md +++ b/README.md @@ -3,18 +3,25 @@ Авторег chat.co + OpenAI-совместимый шлюз на пул аккаунтов. Ферма: `farm.py` (один аккаунт) / `farm2.py` (волна с лентами и атомарным резервом почты). -Шлюз: `shim2.py` — `/v1/chat/completions` (+ SSE), `/v1/models`, `/health`, round-robin по аккаунтам с авторефрешем JWT. +Шлюз: `shim3.py` — OpenAI-совместимый (`/v1/chat/completions`, `/v1/models`, `/health`) с нативными +tools, tool-историей и стримингом; round-robin по аккаунтам с авторефрешем JWT. +Мост: `anth_bridge.py` — Anthropic `/v1/messages` (tools, tool_result, SSE) поверх того же шлюза. +Подробности совместимости: [docs/compat.md](docs/compat.md). ## Что внутри ``` farm.py авторег одного аккаунта: email -> Turnstile -> OTP -> verify -> chatbot -> api keys farm2.py волна: N аккаунтов, K лент, резерв почты через O_CREAT|O_EXCL -shim2.py OpenAI-совместимый шлюз (stdlib http.server, без зависимостей кроме requests) +shim2.py предыдущая версия шлюза (без tools) — оставлена для истории +shim3.py OpenAI-совместимый шлюз: tools, tool_result в истории, SSE с delta.tool_calls +anth_bridge.py Anthropic /v1/messages -> new-api: tool_use блоки, input_json_delta, usage +tests_shim3.py 9 кейсов совместимости против локального шима models.json каталог: display name -> {id, api, credit} (93 модели) healthcheck.py разовая проверка пула: /health + тестовый чат recon/ скрипты разведки UI: логин headful через CDP, дашборд, поиск выбора модели docs/ui-notes.md реверс веб-интерфейса: cookie-авторизация, табы бота, где живёт выбор модели +docs/compat.md что проходит 1:1 с официальными API и где ограничения апстрима ``` ## Как устроен chat.co (реверс) @@ -56,9 +63,12 @@ GET api.chat.co/client/v1/message-allocation -> доступны ```bash export CHATCO_POOL=/opt/chatco-shim/pool.jsonl export CHATCO_PORT=8833 -python3 shim2.py +python3 shim3.py ``` +Канал включён в шлюз new-api (id 119185 `chatco-pool`), поэтому клиентам доступны все +имена каталога без прямого обращения к порту шима. + ``` GET /health -> {ok, accounts, models, credits{email: left}} GET /v1/models -> список моделей chat.co (api-имена) diff --git a/anth_bridge.py b/anth_bridge.py new file mode 100644 index 0000000..a02b89b --- /dev/null +++ b/anth_bridge.py @@ -0,0 +1,411 @@ +#!/usr/bin/env python3 +"""Anthropic /v1/messages <-> new-api /v1/chat/completions. + +Один универсальный мост: любой ключ нашего шлюза работает по протоколу Anthropic +(как api.anthropic.com), включая tools, tool_result, стриминг и usage. + +- auth: x-api-key или Authorization: Bearer, валидация через new-api /v1/models (кэш 120 c) +- stream: SSE-события message_start / content_block_* / message_delta / message_stop +- tools: tool_use блоки, input_json_delta в стриме, tool_result в истории +""" +import json, os, sys, time, urllib.error, urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +UPSTREAM = os.environ.get('AOS_UPSTREAM', 'http://127.0.0.1:48005').rstrip('/') +VALIDATE = os.environ.get('AOS_VALIDATE', UPSTREAM + '/v1/models') +PORT = int(os.environ.get('AOS_PORT', '48018')) +UA = 'anthropic-bridge/2.0' +CACHE_TTL = 120 +_KC = {} + +STOP_MAP = {'stop': 'end_turn', 'length': 'max_tokens', 'tool_calls': 'tool_use', + 'function_call': 'tool_use', 'content_filter': 'end_turn', 'null': 'end_turn'} + + +def log(*a): + print(time.strftime('%H:%M:%S'), *a, flush=True) + + +def key_of(headers): + k = headers.get('x-api-key') or headers.get('X-Api-Key') + if not k: + a = headers.get('authorization') or headers.get('Authorization') or '' + if a.lower().startswith('bearer '): + k = a[7:].strip() + else: + k = a.strip() + return k or '' + + +def key_ok(key): + if not key: + return False + hit = _KC.get(key) + if hit and time.time() - hit < CACHE_TTL: + return True + try: + req = urllib.request.Request(VALIDATE, headers={'authorization': 'Bearer ' + key, 'user-agent': UA}) + with urllib.request.urlopen(req, timeout=10) as r: + ok = r.status == 200 + except Exception: + ok = False + if ok: + _KC[key] = time.time() + return ok + + +def conv_tools(tools): + out = [] + for t in tools or []: + if not isinstance(t, dict): + continue + name = t.get('name') or (t.get('function') or {}).get('name') + if not name: + continue + out.append({'type': 'function', 'function': { + 'name': name, + 'description': t.get('description') or (t.get('function') or {}).get('description') or '', + 'parameters': t.get('input_schema') or t.get('parameters') + or (t.get('function') or {}).get('parameters') or {'type': 'object', 'properties': {}}}}) + return out + + +def conv_tool_choice(tc): + if not isinstance(tc, dict): + return None + t = tc.get('type') + if t == 'auto': + return 'auto' + if t == 'any': + return 'required' + if t == 'none': + return 'none' + if t == 'tool' and tc.get('name'): + return {'type': 'function', 'function': {'name': tc['name']}} + return None + + +def text_of(c): + if isinstance(c, str): + return c + out = [] + for b in c or []: + if isinstance(b, dict) and b.get('type') == 'text': + out.append(b.get('text') or '') + elif isinstance(b, str): + out.append(b) + return '\n'.join(out) + + +def to_openai(body): + msgs = [] + sys_p = body.get('system') + if sys_p: + msgs.append({'role': 'system', 'content': text_of(sys_p)}) + for m in body.get('messages') or []: + role = m.get('role') or 'user' + c = m.get('content') + if isinstance(c, str): + msgs.append({'role': role, 'content': c}) + continue + texts, tool_uses, tool_results, images = [], [], [], [] + for b in c or []: + if not isinstance(b, dict): + continue + ty = b.get('type') + if ty == 'text': + texts.append(b.get('text') or '') + elif ty == 'tool_use': + tool_uses.append({'id': b.get('id') or '', 'type': 'function', + 'function': {'name': b.get('name'), + 'arguments': json.dumps(b.get('input') or {}, ensure_ascii=False)}}) + elif ty == 'tool_result': + inner = b.get('content') + tool_results.append({'role': 'tool', 'tool_call_id': b.get('tool_use_id') or '', + 'content': text_of(inner) if not isinstance(inner, str) else inner}) + elif ty == 'image': + src = b.get('source') or {} + if src.get('type') == 'base64': + images.append({'type': 'image_url', 'image_url': { + 'url': 'data:%s;base64,%s' % (src.get('media_type') or 'image/png', src.get('data') or '')}}) + msgs.extend(tool_results) + if texts or images or tool_uses: + entry = {'role': role} + if images and role == 'user': + entry['content'] = [{'type': 'text', 'text': '\n'.join(texts)}] if texts else [] + entry['content'] += images + else: + entry['content'] = '\n'.join(texts) + if tool_uses: + entry['tool_calls'] = tool_uses + if not entry['content']: + entry['content'] = None + msgs.append(entry) + out = {'model': body.get('model') or '', 'messages': msgs} + if body.get('max_tokens'): + out['max_tokens'] = int(body['max_tokens']) + for k in ('temperature', 'top_p'): + if body.get(k) is not None: + out[k] = body[k] + if body.get('stop_sequences'): + out['stop'] = body['stop_sequences'] + if body.get('metadata', {}).get('user_id'): + out['user'] = body['metadata']['user_id'] + tools = conv_tools(body.get('tools')) + if tools: + out['tools'] = tools + tc = conv_tool_choice(body.get('tool_choice')) + if tc: + out['tool_choice'] = tc + if body.get('stream'): + out['stream'] = True + out['stream_options'] = {'include_usage': True} + return out + + +def up_call(payload, key, timeout=600): + data = json.dumps(payload).encode() + req = urllib.request.Request(UPSTREAM + '/v1/chat/completions', data=data, method='POST', + headers={'content-type': 'application/json', + 'authorization': 'Bearer ' + key, 'user-agent': UA}) + return urllib.request.urlopen(req, timeout=timeout) + + +def err_type(code): + return {400: 'invalid_request_error', 401: 'authentication_error', 403: 'permission_error', + 404: 'not_found_error', 429: 'rate_limit_error'}.get(code, 'api_error') + + +class H(BaseHTTPRequestHandler): + protocol_version = 'HTTP/1.1' + server_version = 'anthropic-bridge/2.0' + + def log_message(self, *a): + pass + + # ---------- io + def _body(self): + n = int(self.headers.get('content-length') or 0) + if not n: + return {} + return json.loads(self.rfile.read(n) or b'{}') + + def sendj(self, code, obj): + d = 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(d))) + self.end_headers() + self.wfile.write(d) + + def err(self, code, message, etype=None): + return self.sendj(code, {'type': 'error', 'error': {'type': etype or err_type(code), 'message': message}}) + + def start_sse(self): + self.send_response(200) + self.send_header('content-type', 'text/event-stream') + self.send_header('cache-control', 'no-cache') + self.send_header('x-accel-buffering', 'no') + self.send_header('transfer-encoding', 'chunked') + self.end_headers() + + def sse(self, payload): + b = payload.encode() + self.wfile.write(b'%x\r\n' % len(b) + b + b'\r\n') + self.wfile.flush() + + def sse_end(self): + self.wfile.write(b'0\r\n\r\n') + self.wfile.flush() + + def ev(self, name, obj): + self.sse('event: %s\ndata: %s\n\n' % (name, json.dumps(obj, ensure_ascii=False))) + + # ---------- routes + def do_GET(self): + p = self.path.rstrip('/').split('?')[0] + if p in ('/health', ''): + return self.sendj(200, {'ok': True, 'upstream': UPSTREAM, 'cached_keys': len(_KC)}) + if p in ('/v1/models', '/models'): + k = key_of(self.headers) + if not key_ok(k): + return self.err(401, 'invalid api key') + req = urllib.request.Request(VALIDATE, headers={'authorization': 'Bearer ' + k, 'user-agent': UA}) + try: + with urllib.request.urlopen(req, timeout=15) as r: + data = json.loads(r.read().decode()) + except Exception as e: + return self.err(502, 'upstream: %s' % e) + return self.sendj(200, {'data': [{'id': m.get('id'), 'type': 'model', + 'display_name': m.get('id')} for m in data.get('data', [])], + 'has_more': False, 'first_id': None, 'last_id': None}) + return self.err(404, 'not found: %s' % p) + + def do_POST(self): + p = self.path.rstrip('/').split('?')[0] + if p not in ('/v1/messages', '/messages', '/v1/messages/count_tokens', '/messages/count_tokens'): + return self.err(404, 'not found: %s' % p) + try: + body = self._body() + except Exception as e: + return self.err(400, 'bad json: %s' % e) + key = key_of(self.headers) + if not key_ok(key): + return self.err(401, 'invalid or missing api key (x-api-key / Authorization)') + + if p.endswith('count_tokens'): + msgs = body.get('messages') or [] + approx = len(json.dumps(msgs, ensure_ascii=False)) // 4 + len(json.dumps(body.get('tools') or [])) // 4 + return self.sendj(200, {'input_tokens': max(1, approx)}) + + try: + payload = to_openai(body) + except Exception as e: + return self.err(400, 'bad request: %s' % e) + if not payload.get('messages'): + return self.err(400, 'messages is required') + + if payload.get('stream'): + return self.stream(payload, key, body) + try: + with up_call(payload, key) as r: + raw = r.read().decode('utf-8', 'replace') + code = r.status + except urllib.error.HTTPError as e: + return self.err(e.code, e.read().decode('utf-8', 'replace')[:1000]) + except Exception as e: + return self.err(502, 'upstream: %s' % e) + if code != 200: + return self.err(code, raw[:1000]) + try: + chat = json.loads(raw) + except Exception: + return self.err(502, 'bad upstream json: %s' % raw[:200]) + return self.sendj(200, self.to_anthropic(chat, body)) + + # ---------- non-stream + def to_anthropic(self, chat, body): + ch = (chat.get('choices') or [{}])[0] + m = ch.get('message') or {} + blocks = [] + if m.get('content'): + blocks.append({'type': 'text', 'text': m['content']}) + for tc in m.get('tool_calls') or []: + fn = tc.get('function') or {} + try: + inp = json.loads(fn.get('arguments') or '{}') + except Exception: + inp = {'input': fn.get('arguments')} + blocks.append({'type': 'tool_use', 'id': tc.get('id') or 'toolu_' + os.urandom(8).hex(), + 'name': fn.get('name'), 'input': inp}) + if not blocks: + blocks = [{'type': 'text', 'text': ''}] + fr = ch.get('finish_reason') or 'stop' + u = chat.get('usage') or {} + return {'id': 'msg_' + os.urandom(12).hex(), 'type': 'message', 'role': 'assistant', + 'model': chat.get('model') or body.get('model') or '', + 'content': blocks, + 'stop_reason': STOP_MAP.get(fr, 'end_turn'), + 'stop_sequence': None, + 'usage': {'input_tokens': u.get('prompt_tokens', 0), + 'output_tokens': u.get('completion_tokens', 0)}} + + # ---------- stream + def stream(self, payload, key, body): + try: + up = up_call(payload, key) + except urllib.error.HTTPError as e: + return self.err(e.code, e.read().decode('utf-8', 'replace')[:1000]) + except Exception as e: + return self.err(502, 'upstream: %s' % e) + + self.start_sse() + mid = 'msg_' + os.urandom(12).hex() + model = payload.get('model') + self.ev('message_start', {'type': 'message_start', 'message': { + 'id': mid, 'type': 'message', 'role': 'assistant', 'model': model, 'content': [], + 'stop_reason': None, 'stop_sequence': None, 'usage': {'input_tokens': 0, 'output_tokens': 0}}}) + self.ev('ping', {'type': 'ping'}) + + idx_text, idx_tool, cur_tool, tool_open = None, 0, {}, {} + in_tokens = out_tokens = 0 + finish = 'stop' + buf = b'' + try: + while True: + chunk = up.read(4096) + if not chunk: + break + buf += chunk + while b'\n' in buf: + line, buf = buf.split(b'\n', 1) + line = line.strip() + if not line.startswith(b'data:'): + continue + data = line[5:].strip() + if data == b'[DONE]': + continue + try: + obj = json.loads(data) + except Exception: + continue + if obj.get('usage'): + in_tokens = obj['usage'].get('prompt_tokens') or in_tokens + out_tokens = obj['usage'].get('completion_tokens') or out_tokens + for ch in obj.get('choices') or []: + d = ch.get('delta') or {} + if d.get('reasoning_content'): + pass # thinking-блок без signature ломает часть клиентов — пропускаем + if d.get('content'): + if idx_text is None: + idx_text = 0 + self.ev('content_block_start', {'type': 'content_block_start', 'index': idx_text, + 'content_block': {'type': 'text', 'text': ''}}) + self.ev('content_block_delta', {'type': 'content_block_delta', 'index': idx_text, + 'delta': {'type': 'text_delta', 'text': d['content']}}) + for tc in d.get('tool_calls') or []: + i = tc.get('index', 0) + fn = tc.get('function') or {} + if i not in tool_open: + if idx_text is not None: + self.ev('content_block_stop', {'type': 'content_block_stop', 'index': idx_text}) + idx_text = None + idx_tool += 1 + tool_open[i] = {'index': idx_tool, 'name': fn.get('name') or ''} + self.ev('content_block_start', { + 'type': 'content_block_start', 'index': idx_tool, + 'content_block': {'type': 'tool_use', + 'id': tc.get('id') or 'toolu_' + os.urandom(8).hex(), + 'name': fn.get('name') or '', 'input': {}}}) + st = tool_open[i] + if fn.get('name') and not st['name']: + st['name'] = fn['name'] + if fn.get('arguments'): + self.ev('content_block_delta', { + 'type': 'content_block_delta', 'index': st['index'], + 'delta': {'type': 'input_json_delta', 'partial_json': fn['arguments']}}) + if ch.get('finish_reason'): + finish = ch['finish_reason'] + except Exception as e: + log('stream error:', type(e).__name__, e) + finally: + try: + up.close() + except Exception: + pass + if idx_text is not None: + self.ev('content_block_stop', {'type': 'content_block_stop', 'index': idx_text}) + for i in sorted(tool_open): + self.ev('content_block_stop', {'type': 'content_block_stop', 'index': tool_open[i]['index']}) + self.ev('message_delta', {'type': 'message_delta', + 'delta': {'stop_reason': STOP_MAP.get(finish, 'end_turn'), 'stop_sequence': None}, + 'usage': {'input_tokens': in_tokens, 'output_tokens': out_tokens}}) + self.ev('message_stop', {'type': 'message_stop'}) + self.sse_end() + + +if __name__ == '__main__': + if len(sys.argv) > 1: + PORT = int(sys.argv[1]) + log('anthropic bridge :%d -> %s' % (PORT, UPSTREAM)) + ThreadingHTTPServer(('127.0.0.1', PORT), H).serve_forever() \ No newline at end of file diff --git a/docs/compat.md b/docs/compat.md new file mode 100644 index 0000000..a48a2ad --- /dev/null +++ b/docs/compat.md @@ -0,0 +1,93 @@ +# Совместимость с официальными API + +Шлюз chat.co умеет три протокола. Ниже — что проходит 1:1, а что ограничено апстримом. + +## Слои + +``` +клиент -> https://api.reformboss.com + /v1/chat/completions -> new-api :48005 -> канал chatco-pool (шим :8833) + /v1/responses -> resp-shim :48019 -> new-api :48005 + /v1/messages -> anth_bridge :48018 -> new-api :48005 +``` + +`shim3.py` — пул аккаунтов chat.co (OpenAI-формат). +`anth_bridge.py` — мост Anthropic `/v1/messages` на тот же new-api: любой ключ шлюза +работает по протоколу Anthropic, включая tools и стриминг. + +## Что проверено (11/11 e2e) + +| Кейс | Результат | +|---|---| +| `GET /v1/models` | 200, все имена канала видны | +| `chat/completions` текст | 200, `usage` с токенами | +| `chat/completions` + `tools` | 200, `finish_reason=tool_calls`, `tool_calls[].function.arguments` — JSON | +| `chat/completions` + `stream` | 200, SSE `data:` чанки, финал `data: [DONE]` | +| `chat/completions` + `stream` + `tools` | 200, дельты `tool_calls` | +| история `assistant.tool_calls` + `role:"tool"` | 200, контекст доходит | +| `messages` текст | 200, `content[{type:text}]`, `usage{input,output}` | +| `messages` + `tools` | 200, `stop_reason=tool_use`, блоки `tool_use` | +| `messages` + `stream` | 200, `message_start` / `content_block_delta` / `message_delta` / `message_stop` | +| `messages` + `stream` + `tools` | 200, `content_block_start(tool_use)` + `input_json_delta` | +| `responses` (`claude-haiku-5-5`, `deepseek-v4.1-flash-1017`) | 200, `status=completed`, `output[]` | +| без ключа | 401 (`authentication_error` / OpenAI-формат) | + +## Как устроены tools + +Апстрим chat.co принимает только `message` и `documentIds` — поля `tools` у него нет. +Поэтому шим: + +1. описывает инструменты текстом в системной части промпта; +2. требует ответ ровно в виде `{"tool_calls":[{"name":...,"arguments":{...}}]}`; +3. парсит JSON (в том числе из ```json-блока и из «голого» объекта), валидирует имена; +4. если модель ответила текстом — один ретрай с напоминанием; +5. отдаёт клиенту обычные `tool_calls` / `tool_use`. + +Отсюда цена: вызов инструмента занимает один лишний круг (ретрай) — до ~20-40 c на +reasoning-моделях. Прямой ответ без tools — 8-12 c. + +## Ограничения + +- **`finish_reason` в стриме** new-api нормализует в `stop` даже когда дельта содержит + `tool_calls` (шим отдаёт `tool_calls` корректно, проверено на :8833). Клиенты, которые + собирают вызовы из дельт, работают; те, кто смотрит только на `finish_reason`, увидят `stop`. +- **`thinking` / `reasoning_content`** апстрим не отдаёт — в Anthropic-мосте блоки + `thinking` не синтезируются (клиенты требуют `signature`). +- **Изображения**: chat.co принимает только текстовый `message`; в истории `image_url` + заменяется пометкой `[image omitted]`. +- **`temperature` / `top_p` / `seed`** апстрим игнорирует — значения принимаются, но не влияют. +- **`n > 1`** выполняется несколькими запросами (до 4), каждый тратит кредиты. +- **`stop` / `max_tokens`** применяются на стороне шима: обрезка по стоп-последовательности + и по `max_tokens*4` символов. +- **`usage`** берётся из апстрима, если он его вернул, иначе оценка `len/4`. +- **Задержка**: 8-12 c на текст (модель + переключение `aiModelId` на аккаунте), 20-40 c + на tool_calls (ретрай). Это ограничение chat.co, не шлюза. + +## Порты и юниты + +| Компонент | Порт | Юнит | +|---|---|---| +| chat.co пул | 8833 | `chatco-shim.service` | +| Anthropic-мост | 48018 | `anth-oa.service` (`/opt/anth-oa/bridge.py`) | +| Responses-мост | 48019 | `resp-shim.service` (`RESP_UPSTREAM=http://127.0.0.1:48005/v1/chat/completions`) | +| new-api | 48005 | `new-api.service` | + +## Переменные + +``` +CHATCO_POOL pool.jsonl (аккаунты: email/bot/key/at/rt) +CHATCO_STATE pool_state.json (обновлённые токены) +CHATCO_PORT 8833 +CHATCO_MSG_LIMIT 8000 (лимит одного message в chat.co) +CHATCO_TIMEOUT 300 +AOS_UPSTREAM http://127.0.0.1:48005 +AOS_PORT 48018 +RESP_UPSTREAM http://127.0.0.1:48005/v1/chat/completions +``` + +## Проверка + +``` +python3 tests_shim3.py # 9 кейсов против шима на 127.0.0.1:8833 +curl -s localhost:8833/health # accounts / models / credits +``` \ No newline at end of file diff --git a/shim3.py b/shim3.py new file mode 100644 index 0000000..af78221 --- /dev/null +++ b/shim3.py @@ -0,0 +1,732 @@ +#!/usr/bin/env python3 +"""chat.co -> OpenAI / Anthropic compatible gateway (pool of accounts). + +Что умеет (максимально близко к официальным API): + +OpenAI: + GET /v1/models + POST /v1/chat/completions — tools (function calling), tool_result в истории, + stream=true с delta.tool_calls, stop/max_tokens/n, + response_format=json_object, usage, ошибки в формате OpenAI + +Anthropic: + POST /v1/messages — tools (tool_use блоки), tool_result, stream=true (SSE-события) + +Служебное: + GET /health + +Апстрим chat.co принимает только одно поле `message` (плюс documentIds), истории и tools у него нет. +Поэтому история склеивается в промпт, а инструменты описываются в промпте и парсятся из ответа. +""" +import json, os, re, sys, threading, time, 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') +MSG_LIMIT = int(os.environ.get('CHATCO_MSG_LIMIT', '8000')) +REQUEST_TIMEOUT = int(os.environ.get('CHATCO_TIMEOUT', '300')) +REMINDER = '\n\n[IMPORTANT] You must call a tool now. Reply with ONLY {"tool_calls":[...]} and no prose.' + +ACCTS = [] # [{email,bot,key,acct_key,at,rt,credits,ts,lock}] +ALLOC_TTL = 120 +RR = [0] + + +def log(*a): + print(time.strftime('%H:%M:%S'), *a, flush=True) + + +# ---------------------------------------------------------------- pool + +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} + try: + json.dump(st, open(STATE_PATH, 'w', encoding='utf-8')) + except Exception as e: + log('save_state', type(e).__name__) + + +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): + r = 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=None): + h = {'Authorization': 'Bearer ' + a['key'], 'Content-Type': 'application/json', 'User-Agent': UA} + return requests.request(method, CLIENT + path, headers=h, json=body, timeout=timeout or REQUEST_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'] + break + a['checked'] = time.time() + except Exception as e: + log('credits', a['email'], type(e).__name__) + return a['credits'] + + +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 + + +# ---------------------------------------------------------------- models + +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 + + +# ---------------------------------------------------------------- prompt building + +def content_text(c): + if isinstance(c, list): + out = [] + for x in c: + if isinstance(x, dict): + if x.get('type') in ('text', 'input_text') and x.get('text'): + out.append(x['text']) + elif x.get('type') == 'image_url': + out.append('[image omitted]') + return ' '.join(out) + return c or '' + + +def tools_block(tools): + """Текстовое описание инструментов + требование вернуть JSON.""" + lines = ['You can call tools. Available tools:'] + for t in tools or []: + fn = t.get('function') if isinstance(t, dict) and 'function' in t else t + if not isinstance(fn, dict): + continue + name = fn.get('name') + desc = (fn.get('description') or '').strip().replace('\n', ' ') + params = fn.get('parameters') or fn.get('input_schema') or {} + lines.append('- %s: %s' % (name, desc[:300])) + props = (params.get('properties') or {}) + if props: + meta = [] + for k, v in props.items(): + typ = v.get('type', 'any') + req = ' (required)' if k in (params.get('required') or []) else '' + meta.append('%s:%s%s' % (k, typ, req)) + lines.append(' arguments: ' + ', '.join(meta)) + lines.append('If you need a tool, reply with ONLY this JSON and nothing else:') + lines.append('{"tool_calls":[{"name":"","arguments":{"":}}]}') + lines.append('Never wrap that JSON in markdown. If no tool is needed, answer normally.') + return '\n'.join(lines) + + +def flatten(messages, tools=None, json_mode=False): + """Склеивает историю OpenAI/Anthropic в один промпт чат.co.""" + system, parts = None, [] + for m in messages or []: + role = m.get('role') + c = content_text(m.get('content')) + if role == 'system': + system = (system + '\n' + c) if system else c + elif role in ('tool', 'function'): + name = m.get('name') or m.get('tool_call_id') or 'tool' + parts.append('[TOOL RESULT %s] %s' % (name, c)) + elif role == 'assistant': + calls = m.get('tool_calls') or [] + if calls: + rendered = [] + for cl in calls: + fn = cl.get('function') or {} + rendered.append('%s(%s)' % (fn.get('name'), fn.get('arguments'))) + parts.append('Assistant called: ' + '; '.join(rendered)) + elif c: + parts.append('Assistant: ' + c) + else: + parts.append(c if len(messages) == 1 else 'User: ' + c) + if tools: + block = tools_block(tools) + system = (system + '\n\n' + block) if system else block + if json_mode: + j = 'Reply with a single valid JSON object and nothing else.' + system = (system + '\n\n' + j) if system else j + prompt = '\n\n'.join(parts) if len(parts) > 1 else (parts[0] if parts else '') + return system, prompt + + +TOOL_JSON_RE = re.compile(r'\{[^{}]*"tool_calls"\s*:\s*\[[\s\S]*?\]\s*\}', re.S) + + +def parse_tool_calls(text, tools): + """Достаёт tool_calls из текста ответа; валидирует имена по переданным инструментам.""" + if not text or not tools: + return None, text + allowed = set() + for t in tools: + fn = t.get('function') if isinstance(t, dict) and 'function' in t else t + if isinstance(fn, dict) and fn.get('name'): + allowed.add(fn['name']) + cleaned = re.sub(r'```(?:json)?\s*([\s\S]*?)```', lambda m: m.group(1), text).strip() + for src in (text, cleaned): + cand = TOOL_JSON_RE.search(src) + if cand: + try: + return _calls_from(json.loads(cand.group(0)), allowed, text) + except Exception: + pass + st = src.strip() + if st.startswith('{') and st.endswith('}'): + try: + return _calls_from(json.loads(st), allowed, text) + except Exception: + pass + for m in re.finditer(r'\{[\s\S]*?\}', cleaned): + try: + obj = json.loads(m.group(0)) + except Exception: + continue + if isinstance(obj, dict) and obj.get('name') and ('arguments' in obj or 'parameters' in obj): + return _calls_from({'tool_calls': [obj]}, allowed, text) + return None, text + +def _calls_from(obj, allowed, text): + calls = obj.get('tool_calls') or ([obj['tool_call']] if isinstance(obj.get('tool_call'), dict) else None) + if not calls and obj.get('name'): + calls = [obj] + if not calls: + return None, text + out = [] + for c in calls: + if not isinstance(c, dict): + continue + name = c.get('name') or (c.get('function') or {}).get('name') + if not name or (allowed and name not in allowed): + return None, text + args = c.get('arguments') + if args is None: + args = (c.get('function') or {}).get('arguments') + if isinstance(args, str): + try: + json.loads(args) + except Exception: + args = json.dumps({'input': args}) + else: + args = json.dumps(args or {}, ensure_ascii=False) + out.append({'id': 'call_' + uuid.uuid4().hex[:20], 'type': 'function', + 'function': {'name': name, 'arguments': args}}) + if not out: + return None, text + leftover = TOOL_JSON_RE.sub('', text).strip() + return out, leftover + + +def apply_stop(text, stops): + if not stops: + return text, None + best, hit = None, None + for s in stops: + if not s: + continue + i = text.find(s) + if i >= 0 and (best is None or i < best): + best, hit = i, s + if best is None: + return text, None + return text[:best], hit + + +def cut_tokens(text, max_tokens): + if not max_tokens: + return text + try: + n = int(max_tokens) + except Exception: + return text + if n <= 0: + return text + approx = n * 4 + return text if len(text) <= approx else text[:approx] + + +# ---------------------------------------------------------------- upstream + +def ask(model_name, prompt, system=None, timeout=None, tools=None, json_mode=False): + """Один запрос в chat.co. Возвращает dict с текстом, tool_calls и метаданными.""" + disp, m = resolve_model(model_name) + if not m: + raise KeyError(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[:MSG_LIMIT]}, timeout=timeout) + if rr.status_code not in (200, 201): + raise RuntimeError('msg %s %s' % (rr.status_code, rr.text[:200])) + data = rr.json()['data'] + br = data.get('botResponse') or {} + text = br.get('content') or '' + a['credits'] -= float(m.get('credit') or 5) + usage = br.get('usage') or {} + return {'text': text, 'model': disp, 'api': m['api'], 'cid': cid, 'account': a['email'], + 'usage': usage, 'raw': data} + + +def tokens_for(prompt, text, upstream_usage=None): + if upstream_usage: + it = upstream_usage.get('promptTokens') or upstream_usage.get('inputTokens') + ot = upstream_usage.get('completionTokens') or upstream_usage.get('outputTokens') + if it and ot: + return int(it), int(ot) + return max(1, len(prompt) // 4), max(1, len(text) // 4) + + +# ---------------------------------------------------------------- HTTP + +class H(BaseHTTPRequestHandler): + protocol_version = 'HTTP/1.1' + server_version = 'chatco-shim/3.0' + + def log_message(self, *a): + pass + + def _body(self): + n = int(self.headers.get('Content-Length') or 0) + raw = self.rfile.read(n) if n else b'' + return json.loads(raw or b'{}') + + def sendj(self, code, obj, extra=None): + 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))) + for k, v in (extra or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(b) + + def err_openai(self, code, message, etype='invalid_request_error', param=None, ecode=None): + return self.sendj(code, {'error': {'message': message, 'type': etype, 'param': param, 'code': ecode}}) + + def start_sse(self): + self.send_response(200) + self.send_header('Content-Type', 'text/event-stream') + self.send_header('Cache-Control', 'no-cache') + self.send_header('X-Accel-Buffering', 'no') + self.send_header('Transfer-Encoding', 'chunked') + self.end_headers() + + def sse(self, payload): + b = payload.encode() if isinstance(payload, str) else payload + self.wfile.write(b'%x\r\n' % len(b) + b + b'\r\n') + self.wfile.flush() + + def sse_end(self): + self.wfile.write(b'0\r\n\r\n') + self.wfile.flush() + + # ---------------- GET + def do_GET(self): + p = self.path.rstrip('/').split('?')[0] + 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), 'version': '3.0', + 'credits': {a['email']: round(a['credits'], 1) for a in ACCTS}}) + return self.err_openai(404, 'not found', 'not_found_error') + + # ---------------- POST + def do_POST(self): + p = self.path.rstrip('/').split('?')[0] + try: + if p in ('/v1/messages', '/messages'): + return self.anthropic() + if p in ('/v1/chat/completions', '/chat/completions'): + return self.chat() + if p in ('/v1/responses', '/responses'): + return self.openai_responses() + return self.err_openai(404, 'unknown path %s' % p, 'not_found_error') + except Exception as e: # страховка от необработанных исключений + log('POST %s EXC %s' % (p, type(e).__name__)) + return self.err_openai(500, 'internal error: %s' % e, 'server_error') + + # ---------------- OpenAI chat/completions + def chat(self): + try: + req = self._body() + except Exception as e: + return self.err_openai(400, 'bad json: %s' % e) + model = req.get('model') or '' + messages = req.get('messages') or [] + if not messages: + return self.err_openai(400, 'messages is required', param='messages') + tools = req.get('tools') or [] + tool_choice = req.get('tool_choice') + if tool_choice == 'none': + tools = [] + json_mode = ((req.get('response_format') or {}).get('type') == 'json_object') + system, prompt = flatten(messages, tools=tools, json_mode=json_mode) + n = max(1, min(int(req.get('n') or 1), 4)) + try: + first = ask(model, prompt, system, tools=tools, json_mode=json_mode) + except KeyError: + return self.err_openai(404, 'model not found: %s' % model, 'invalid_request_error', 'model') + except RuntimeError as e: + msg = str(e) + if 'no accounts' in msg: + return self.err_openai(429, 'no accounts with credits left', 'rate_limit_error') + return self.err_openai(502, msg, 'upstream_error') + if tools and not parse_tool_calls(first['text'], tools)[0]: + try: + reminder = prompt + REMINDER + retry = ask(model, reminder, system, tools=tools, json_mode=json_mode) + if parse_tool_calls(retry['text'], tools)[0]: + first = retry + except Exception: + pass + results = [first] + for _ in range(n - 1): + try: + results.append(ask(model, prompt, system, tools=tools, json_mode=json_mode)) + except Exception: + break + + mid = 'chatcmpl-' + uuid.uuid4().hex[:24] + created = int(time.time()) + choices = [] + for i, r in enumerate(results): + text, cut = apply_stop(r['text'], req.get('stop')) + text = cut_tokens(text, req.get('max_tokens') or req.get('max_completion_tokens')) + calls, leftover = parse_tool_calls(text, tools) + msg = {'role': 'assistant'} + if calls: + msg['content'] = leftover or None + msg['tool_calls'] = calls + finish = 'tool_calls' + else: + msg['content'] = text + finish = 'stop' + if cut: + finish = 'stop' + choices.append({'index': i, 'message': msg, 'finish_reason': finish}) + it, ot = tokens_for(prompt, ' '.join(r['text'] for r in results)) + usage = {'prompt_tokens': it, 'completion_tokens': ot, 'total_tokens': it + ot} + + if not req.get('stream'): + body = {'id': mid, 'object': 'chat.completion', 'created': created, 'model': first['api'], + 'choices': choices, 'usage': usage, 'x_chatco_account': first['account']} + return self.sendj(200, body, {'X-Request-Id': mid}) + + # ---- stream + self.start_sse() + + def chunk(delta, fin=None, idx=0): + self.sse('data: ' + json.dumps({'id': mid, 'object': 'chat.completion.chunk', 'created': created, + 'model': first['api'], + 'choices': [{'index': idx, 'delta': delta, 'finish_reason': fin}]}, + ensure_ascii=False) + '\n\n') + for i, ch in enumerate(choices): + chunk({'role': 'assistant', 'content': ''}, None, i) + msg = ch['message'] + if msg.get('tool_calls'): + for j, c in enumerate(msg['tool_calls']): + chunk({'tool_calls': [{'index': j, 'id': c['id'], 'type': 'function', + 'function': {'name': c['function']['name'], + 'arguments': c['function']['arguments']}}]}, + None, i) + chunk({}, 'tool_calls', i) + else: + text = msg.get('content') or '' + step = max(1, len(text) // 40) if text else 1 + for k in range(0, len(text), step): + chunk({'content': text[k:k + step]}, None, i) + chunk({}, 'stop', i) + if req.get('stream_options', {}).get('include_usage'): + self.sse('data: ' + json.dumps({'id': mid, 'object': 'chat.completion.chunk', 'created': created, + 'model': first['api'], 'choices': [], 'usage': usage}) + '\n\n') + self.sse('data: [DONE]\n\n') + self.sse_end() + + # ---------------- OpenAI responses (тонкая обёртка) + def openai_responses(self): + try: + req = self._body() + except Exception as e: + return self.err_openai(400, 'bad json: %s' % e) + msgs = [] + inp = req.get('input') + if isinstance(inp, str): + msgs = [{'role': 'user', 'content': inp}] + elif isinstance(inp, list): + for it in inp: + if isinstance(it, dict) and it.get('role'): + msgs.append({'role': it['role'], 'content': content_text(it.get('content'))}) + if req.get('instructions'): + msgs.insert(0, {'role': 'system', 'content': req['instructions']}) + if not msgs: + return self.err_openai(400, 'input is required', param='input') + system, prompt = flatten(msgs) + try: + r = ask(req.get('model') or '', prompt, system) + except KeyError: + return self.err_openai(404, 'model not found: %s' % req.get('model')) + except RuntimeError as e: + return self.err_openai(502, str(e), 'upstream_error') + rid = 'resp_' + uuid.uuid4().hex[:24] + it, ot = tokens_for(prompt, r['text']) + self.sendj(200, {'id': rid, 'object': 'response', 'created_at': int(time.time()), 'model': r['api'], + 'status': 'completed', + 'output': [{'id': 'msg_' + uuid.uuid4().hex[:16], 'type': 'message', 'role': 'assistant', + 'status': 'completed', + 'content': [{'type': 'output_text', 'text': r['text'], 'annotations': []}]}], + 'usage': {'input_tokens': it, 'output_tokens': ot, 'total_tokens': it + ot}}) + + # ---------------- Anthropic messages + def anthropic(self): + try: + req = self._body() + except Exception as e: + return self.sendj(400, {'type': 'error', 'error': {'type': 'invalid_request_error', + 'message': 'bad json: %s' % e}}) + system = req.get('system') + if isinstance(system, list): + system = '\n'.join(x.get('text', '') for x in system if isinstance(x, dict)) + tools = req.get('tools') or [] + if req.get('tool_choice', {}).get('type') == 'none': + tools = [] + msgs = [] + for m in req.get('messages') or []: + role = m.get('role') + c = m.get('content') + if isinstance(c, list): + texts, tool_results, tool_uses = [], [], [] + for b in c: + if not isinstance(b, dict): + continue + t = b.get('type') + if t == 'text': + texts.append(b.get('text', '')) + elif t == 'tool_result': + body = b.get('content') + if isinstance(body, list): + body = ' '.join(x.get('text', '') for x in body if isinstance(x, dict)) + tool_results.append({'role': 'tool', 'tool_call_id': b.get('tool_use_id'), + 'content': body or ''}) + elif t == 'tool_use': + tool_uses.append({'id': b.get('id'), 'type': 'function', + 'function': {'name': b.get('name'), + 'arguments': json.dumps(b.get('input') or {}, ensure_ascii=False)}}) + if tool_results: + msgs.extend(tool_results) + continue + entry = {'role': role, 'content': ' '.join(texts)} + if tool_uses: + entry['tool_calls'] = tool_uses + msgs.append(entry) + else: + msgs.append({'role': role, 'content': c or ''}) + system_p, prompt = flatten(msgs, tools=tools) + if system: + system_p = ((system_p + '\n\n' + system) if system_p else system)[:20000] + model = req.get('model') or '' + try: + r = ask(model, prompt, system_p, tools=tools) + except KeyError: + return self.sendj(404, {'type': 'error', 'error': {'type': 'not_found_error', + 'message': 'model not found: %s' % model}}) + except RuntimeError as e: + return self.sendj(502, {'type': 'error', 'error': {'type': 'api_error', 'message': str(e)}}) + if tools and not parse_tool_calls(r['text'], tools)[0]: + try: + reminder = prompt + REMINDER + r2 = ask(model, reminder, system_p, tools=tools) + if parse_tool_calls(r2['text'], tools)[0]: + r = r2 + except Exception: + pass + text, cut = apply_stop(r['text'], req.get('stop_sequences')) + text = cut_tokens(text, req.get('max_tokens')) + calls, leftover = parse_tool_calls(text, tools) + it, ot = tokens_for(prompt, text) + + blocks = [] + if calls: + if leftover: + blocks.append({'type': 'text', 'text': leftover}) + for c in calls: + try: + inp = json.loads(c['function']['arguments']) + except Exception: + inp = {'input': c['function']['arguments']} + blocks.append({'type': 'tool_use', 'id': c['id'], 'name': c['function']['name'], 'input': inp}) + stop_reason = 'tool_use' + else: + blocks = [{'type': 'text', 'text': text}] + stop_reason = 'stop_sequence' if cut else 'end_turn' + + mid = 'msg_' + uuid.uuid4().hex[:24] + if not req.get('stream'): + return self.sendj(200, {'id': mid, 'type': 'message', 'role': 'assistant', 'model': model or r['api'], + 'content': blocks, 'stop_reason': stop_reason, 'stop_sequence': cut, + 'usage': {'input_tokens': it, 'output_tokens': ot}, + 'x_chatco_account': r['account']}) + + self.start_sse() + + def ev(name, obj): + self.sse('event: %s\ndata: %s\n\n' % (name, json.dumps(obj, ensure_ascii=False))) + ev('message_start', {'type': 'message_start', 'message': {'id': mid, 'type': 'message', 'role': 'assistant', + 'model': model or r['api'], 'content': [], + 'stop_reason': None, 'stop_sequence': None, + 'usage': {'input_tokens': it, 'output_tokens': 0}}}) + if calls: + if leftover: + ev('content_block_start', {'type': 'content_block_start', 'index': 0, + 'content_block': {'type': 'text', 'text': ''}}) + ev('content_block_delta', {'type': 'content_block_delta', 'index': 0, + 'delta': {'type': 'text_delta', 'text': leftover}}) + ev('content_block_stop', {'type': 'content_block_stop', 'index': 0}) + idx = 1 + else: + idx = 0 + for c in calls: + try: + inp = json.loads(c['function']['arguments']) + except Exception: + inp = {'input': c['function']['arguments']} + ev('content_block_start', {'type': 'content_block_start', 'index': idx, + 'content_block': {'type': 'tool_use', 'id': c['id'], + 'name': c['function']['name'], 'input': {}}}) + ev('content_block_delta', {'type': 'content_block_delta', 'index': idx, + 'delta': {'type': 'input_json_delta', + 'partial_json': json.dumps(inp, ensure_ascii=False)}}) + ev('content_block_stop', {'type': 'content_block_stop', 'index': idx}) + idx += 1 + else: + ev('content_block_start', {'type': 'content_block_start', 'index': 0, + 'content_block': {'type': 'text', 'text': ''}}) + step = max(1, len(text) // 40) if text else 1 + for k in range(0, len(text), step): + ev('content_block_delta', {'type': 'content_block_delta', 'index': 0, + 'delta': {'type': 'text_delta', 'text': text[k:k + step]}}) + ev('content_block_stop', {'type': 'content_block_stop', 'index': 0}) + ev('message_delta', {'type': 'message_delta', + 'delta': {'stop_reason': stop_reason, 'stop_sequence': cut}, + 'usage': {'output_tokens': ot}}) + ev('message_stop', {'type': 'message_stop'}) + self.sse_end() + + +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 shim v3 :%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 diff --git a/tests_shim3.py b/tests_shim3.py new file mode 100644 index 0000000..838a05d --- /dev/null +++ b/tests_shim3.py @@ -0,0 +1,66 @@ +import json, sys, time, urllib.request, urllib.error +sys.stdout.reconfigure(encoding='utf-8', errors='replace') +B='http://127.0.0.1:8833' +TOOLS=[{"type":"function","function":{"name":"get_weather","description":"Weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}] + +def post(path, body, raw=False): + req=urllib.request.Request(B+path, data=json.dumps(body).encode(), headers={'content-type':'application/json'}) + t0=time.time() + try: + r=urllib.request.urlopen(req, timeout=280) + data=r.read().decode() + return r.status, data, time.time()-t0 + except urllib.error.HTTPError as e: + return e.code, e.read().decode(), time.time()-t0 + +def j(d): + try: return json.loads(d) + except Exception: return None + +print('=== 1 plain') +c,d,t=post('/v1/chat/completions', {"model":"claude-haiku-5-5","max_tokens":40,"messages":[{"role":"user","content":"Ответь ровно: OK1"}]}) +o=j(d); print(c, '%.1fs'%t, '|', (o or {}).get('choices',[{}])[0].get('message',{}).get('content','')[:50], '| usage', (o or {}).get('usage')) + +print('=== 2 stream') +c,d,t=post('/v1/chat/completions', {"model":"claude-haiku-5-5","max_tokens":40,"stream":True,"stream_options":{"include_usage":True},"messages":[{"role":"user","content":"Считай до 3"}]}) +lines=[l for l in d.split('\n') if l.startswith('data: ')] +print(c, '%.1fs'%t, 'chunks', len(lines), '| done', 'data: [DONE]' in d, '| usage_in_stream', 'usage' in d) + +print('=== 3 tools') +c,d,t=post('/v1/chat/completions', {"model":"claude-haiku-5-5","max_tokens":200,"tools":TOOLS,"tool_choice":"auto", + "messages":[{"role":"user","content":"Какая погода в Берлине? Используй инструмент."}]}) +o=j(d); ch=(o or {}).get('choices',[{}])[0]; msg=ch.get('message',{}) +tc=msg.get('tool_calls') or [] +print(c, '%.1fs'%t, 'finish', ch.get('finish_reason'), 'calls', len(tc)) +for x in tc: print(' ', x['function']['name'], x['function']['arguments'][:80]) + +print('=== 4 tools+stream') +c,d,t=post('/v1/chat/completions', {"model":"claude-haiku-5-5","max_tokens":200,"stream":True,"tools":TOOLS, + "messages":[{"role":"user","content":"Погода в Париже? Вызови инструмент."}]}) +print(c, '%.1fs'%t, 'tool_calls_in_sse', 'tool_calls' in d, '| finish tool_calls', '"tool_calls"' in d) + +print('=== 5 tool_result roundtrip') +msgs=[{"role":"user","content":"Погода в Берлине?"}, + {"role":"assistant","content":None,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Berlin\"}"}}]}, + {"role":"tool","tool_call_id":"call_1","name":"get_weather","content":"{\"temp\":7,\"sky\":\"cloudy\"}"}, + {"role":"user","content":"Скажи температуру одним словом."}] +c,d,t=post('/v1/chat/completions', {"model":"claude-haiku-5-5","max_tokens":60,"tools":TOOLS,"messages":msgs}) +o=j(d); print(c, '%.1fs'%t, '|', (o or {}).get('choices',[{}])[0].get('message',{}).get('content','')[:70]) + +print('=== 6 anthropic messages') +c,d,t=post('/v1/messages', {"model":"claude-haiku-5-5","max_tokens":60,"messages":[{"role":"user","content":"Ответь: ANT-OK"}]}) +o=j(d); print(c, '%.1fs'%t, 'type', (o or {}).get('type'), '|', json.dumps((o or {}).get('content'), ensure_ascii=False)[:90]) + +print('=== 7 anthropic tools') +AT=[{"name":"get_weather","description":"Weather for a city","input_schema":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}] +c,d,t=post('/v1/messages', {"model":"claude-haiku-5-5","max_tokens":200,"tools":AT, + "messages":[{"role":"user","content":"Погода в Риме? Вызови инструмент."}]}) +o=j(d); print(c, '%.1fs'%t, 'stop_reason', (o or {}).get('stop_reason'), '| blocks', [b.get('type') for b in ((o or {}).get('content') or [])]) + +print('=== 8 responses api') +c,d,t=post('/v1/responses', {"model":"claude-haiku-5-5","input":"Ответь: RESP-OK"}) +o=j(d); print(c, '%.1fs'%t, 'status', (o or {}).get('status'), '|', json.dumps((o or {}).get('output'), ensure_ascii=False)[:100]) + +print('=== 9 unknown model') +c,d,t=post('/v1/chat/completions', {"model":"nope-model-xyz","messages":[{"role":"user","content":"hi"}]}) +print(c, '%.1fs'%t, d[:110])