shim3: native tools, tool_result, SSE tool_calls; anthropic bridge; docs/compat.md
This commit is contained in:
@@ -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":"<tool_name>","arguments":{"<arg>":<value>}}]}')
|
||||
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()
|
||||
Reference in New Issue
Block a user