411 lines
17 KiB
Python
411 lines
17 KiB
Python
#!/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() |