Files
hearth/package/affine-chatgpt/src/affine_gateway.py
T
yukkop 50c4efc09b
runner nix smoke / nix label and flake smoke (push) Failing after 1m12s
gpt in affine
2026-11-01 11:21:28 +00:00

613 lines
23 KiB
Python

"""Minimal OpenAI Responses-compatible gateway for AFFiNE."""
import hmac
import json
import os
import re
import socket
import stat
import threading
import time
from typing import cast
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from urllib.parse import urlsplit
import requests
import affine_chatgpt as auth
MAX_BODY = 2 * 1024 * 1024
MAX_EVENT = 8 * 1024 * 1024
CONNECT_TIMEOUT = 15
READ_TIMEOUT = 90
SOCKET_TIMEOUT = 95
HEADER_TIMEOUT = 10
CATALOG_TTL = 300
MAX_CONCURRENT = 16
MAX_CONNECTIONS = 32
NAMESPACE = "affine"
NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,128}$")
NAMESPACE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
SAFE_UPSTREAM_CODES = {
"invalid_request_error",
"model_not_found",
"rate_limit_exceeded",
"server_error",
"insufficient_quota",
}
IGNORED_FIELDS = {
"max_output_tokens",
"max_tool_calls",
"metadata",
"moderation",
"multi_agent",
"prompt_cache_retention",
"safety_identifier",
"temperature",
"top_logprobs",
"top_p",
"truncation",
"user",
}
REJECTED_FIELDS = {"background", "conversation", "previous_response_id", "prompt"}
class GatewayError(Exception):
"""Expected client/upstream failure safe for public output."""
def __init__(self, status, code):
super().__init__(code)
self.status = status
self.code = code
def read_gateway_key(path):
try:
info = path.lstat()
except OSError:
raise auth.AppError("invalid_gateway_key") from None
if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
raise auth.AppError("invalid_gateway_key")
try:
descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(descriptor, "r", encoding="utf-8") as stream:
value = stream.read(4097).strip()
except (OSError, UnicodeError):
raise auth.AppError("invalid_gateway_key") from None
if len(value) < 32 or len(value) > 4096 or "\n" in value or "\r" in value:
raise auth.AppError("invalid_gateway_key")
return value
def new_session():
session = requests.Session()
session.trust_env = False
return session
def _response_json(response, code):
if response.is_redirect:
raise GatewayError(response.status_code, "upstream_redirect")
try:
value = response.json()
except (requests.RequestException, ValueError):
raise GatewayError(502, code) from None
if not isinstance(value, dict):
raise GatewayError(502, code)
return value
class Provider:
def __init__(self, state_dir, session=None, now=time.time):
self.state_dir = state_dir
self.session = session or new_session()
self.now = now
self.catalog = None
self.catalog_at = 0
self.lock = threading.Lock()
def credentials(self):
with auth.credential_lock(self.state_dir) as directory:
path = auth.credentials_path(directory)
creds = auth.read_credentials(directory)
if not isinstance(creds, dict):
raise auth.AppError("not_authorized")
if creds.get("expires_at", 0) <= self.now() + 120:
creds = auth.refresh(self.session, path, creds)
return creds
def ready(self):
self.credentials()
def models(self):
with self.lock:
if self.catalog is not None and self.now() - self.catalog_at < CATALOG_TTL:
return list(self.catalog)
creds = self.credentials()
response = auth._request(
self.session,
"GET",
auth.MODELS_URL,
headers={"Authorization": "Bearer " + creds["access_token"]},
)
if response.is_redirect or response.status_code != 200:
raise GatewayError(response.status_code, "upstream_models_error")
data = _response_json(response, "upstream_models_invalid")
entries = data.get("models")
if not isinstance(entries, list):
raise GatewayError(502, "upstream_models_invalid")
catalog = []
for item in entries:
if (
isinstance(item, dict)
and item.get("visibility") == "list"
and isinstance(item.get("slug"), str)
and item["slug"]
and isinstance(item.get("display_name"), str)
):
catalog.append((item["slug"], item["display_name"]))
self.catalog = catalog
self.catalog_at = self.now()
return list(catalog)
def response(self, body):
if auth.RESPONSES_URL != "https://api.openai.com/v1/responses":
raise GatewayError(500, "endpoint_not_allowed")
creds = self.credentials()
try:
return self.session.request(
"POST",
auth.RESPONSES_URL,
headers={
"Authorization": "Bearer " + creds["access_token"],
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
json=body,
stream=True,
timeout=(CONNECT_TIMEOUT, READ_TIMEOUT),
allow_redirects=False,
)
except requests.RequestException:
raise GatewayError(502, "upstream_network_error") from None
def _copy_keys(value, allowed):
return {key: value[key] for key in allowed if key in value}
def _normalize_content(content, role):
if isinstance(content, str):
return [{"type": "output_text" if role == "assistant" else "input_text", "text": content}]
if not isinstance(content, list) or not content:
raise GatewayError(400, "invalid_input")
result = []
for part in content:
if not isinstance(part, dict) or part.get("type") not in {"input_text", "output_text"}:
raise GatewayError(400, "unsupported_media")
if not isinstance(part.get("text"), str):
raise GatewayError(400, "invalid_input")
result.append({"type": part["type"], "text": part["text"]})
return result
def _normalize_item(item):
if not isinstance(item, dict):
raise GatewayError(400, "invalid_input")
item_type = item.get("type")
if item_type in (None, "message"):
role = item.get("role")
if role == "system":
role = "developer"
if role not in {"user", "assistant", "developer"}:
raise GatewayError(400, "invalid_input")
return {
"type": "message",
"role": role,
"content": _normalize_content(item.get("content"), role),
}
if item_type == "function_call":
result = _copy_keys(item, {"id", "call_id", "name", "arguments", "namespace", "status"})
if not all(isinstance(result.get(key), str) and result[key] for key in ("call_id", "name", "arguments")):
raise GatewayError(400, "invalid_input")
result["type"] = item_type
return result
if item_type == "function_call_output":
result = _copy_keys(item, {"id", "call_id", "output", "status"})
if not isinstance(result.get("call_id"), str) or not result["call_id"] or not isinstance(result.get("output"), str):
raise GatewayError(400, "invalid_input")
result["type"] = item_type
return result
if item_type == "reasoning":
result = _copy_keys(item, {"id", "summary", "content", "encrypted_content", "status"})
if not any(key in result for key in ("summary", "content", "encrypted_content")):
raise GatewayError(400, "invalid_input")
result["type"] = item_type
return result
raise GatewayError(400, "unsupported_input_type")
def _normalize_inner_tool(tool):
if not isinstance(tool, dict) or tool.get("type") not in {"function", "custom"}:
raise GatewayError(400, "unsupported_tool")
name = tool.get("name")
if not isinstance(name, str) or not NAME_RE.fullmatch(name):
raise GatewayError(400, "invalid_tool")
if tool["type"] == "function":
allowed = {"type", "name", "description", "parameters", "strict"}
else:
allowed = {"type", "name", "description", "format"}
if set(tool) - allowed:
raise GatewayError(400, "unsupported_tool_field")
return _copy_keys(tool, allowed)
def _normalize_tools(tools):
if not isinstance(tools, list) or not tools:
raise GatewayError(400, "invalid_tools")
if all(isinstance(tool, dict) and tool.get("type") in {"function", "custom"} for tool in tools):
return [{
"type": "namespace",
"name": NAMESPACE,
"description": "Functions provided and executed by AFFiNE.",
"tools": [_normalize_inner_tool(tool) for tool in tools],
}]
result = []
for namespace in tools:
if not isinstance(namespace, dict) or set(namespace) - {"type", "name", "description", "tools"}:
raise GatewayError(400, "unsupported_tool")
name = namespace.get("name")
nested = namespace.get("tools")
if namespace.get("type") != "namespace" or not isinstance(name, str) or not NAMESPACE_RE.fullmatch(name):
raise GatewayError(400, "unsupported_tool")
if not isinstance(namespace.get("description"), str) or not isinstance(nested, list) or not nested:
raise GatewayError(400, "invalid_tools")
result.append({
"type": "namespace",
"name": name,
"description": namespace["description"],
"tools": [_normalize_inner_tool(tool) for tool in nested],
})
return result
def _normalize_choice(choice, had_flat_tools):
if isinstance(choice, str) and choice in {"auto", "none", "required"}:
return choice
if not isinstance(choice, dict):
raise GatewayError(400, "unsupported_tool_choice")
result = dict(choice)
if result.get("type") in {"function", "custom"} and had_flat_tools:
if set(result) - {"type", "name"} or not isinstance(result.get("name"), str):
raise GatewayError(400, "unsupported_tool_choice")
result["namespace"] = NAMESPACE
return result
if result.get("type") in {"function", "custom"}:
if set(result) - {"type", "name", "namespace"}:
raise GatewayError(400, "unsupported_tool_choice")
return result
raise GatewayError(400, "unsupported_tool_choice")
def normalize_request(value, eligible):
if not isinstance(value, dict):
raise GatewayError(400, "invalid_json")
allowed = {"model", "input", "instructions", "tools", "tool_choice", "store", "stream"}
unknown = set(value) - allowed - IGNORED_FIELDS - REJECTED_FIELDS
if set(value) & REJECTED_FIELDS:
raise GatewayError(400, "unsupported_parameter")
if unknown:
raise GatewayError(400, "unsupported_parameter")
if "stream" in value and not isinstance(value["stream"], bool):
raise GatewayError(400, "invalid_stream")
if "store" in value and not isinstance(value["store"], bool):
raise GatewayError(400, "invalid_store")
model = value.get("model")
if not isinstance(model, str) or model not in eligible:
raise GatewayError(400, "model_not_available")
incoming = value.get("input")
if not isinstance(incoming, list) or not incoming:
raise GatewayError(400, "invalid_input")
result = {
"model": model,
"input": [_normalize_item(item) for item in incoming],
"store": False,
"stream": True,
}
if "instructions" in value:
if not isinstance(value["instructions"], str):
raise GatewayError(400, "invalid_instructions")
result["instructions"] = value["instructions"]
if "tools" in value:
flat = all(isinstance(tool, dict) and tool.get("type") in {"function", "custom"} for tool in value["tools"]) if isinstance(value["tools"], list) else False
result["tools"] = _normalize_tools(value["tools"])
if "tool_choice" in value:
result["tool_choice"] = _normalize_choice(value["tool_choice"], flat)
elif "tool_choice" in value:
raise GatewayError(400, "unsupported_tool_choice")
return result
def _events(response):
buffer = b""
try:
for chunk in response.iter_content(chunk_size=16384):
if not chunk:
continue
buffer += chunk
if len(buffer) > MAX_EVENT:
raise GatewayError(502, "upstream_stream_invalid")
while True:
positions = [(buffer.find(b"\n\n"), 2), (buffer.find(b"\r\n\r\n"), 4)]
positions = [(position, size) for position, size in positions if position >= 0]
if not positions:
break
position, size = min(positions)
raw, buffer = buffer[: position + size], buffer[position + size :]
yield raw, _event_data(raw)
if buffer.strip():
raise GatewayError(502, "upstream_stream_interrupted")
except requests.RequestException:
raise GatewayError(502, "upstream_stream_interrupted") from None
def _event_data(raw):
data = []
for line in raw.replace(b"\r\n", b"\n").split(b"\n"):
if line.startswith(b"data:"):
data.append(line[5:].lstrip())
if not data or b"\n".join(data) == b"[DONE]":
return None
try:
value = json.loads(b"\n".join(data))
except (ValueError, UnicodeError):
raise GatewayError(502, "upstream_stream_invalid") from None
if not isinstance(value, dict) or not isinstance(value.get("type"), str):
raise GatewayError(502, "upstream_stream_invalid")
return value
def _upstream_error(response):
code = "upstream_http_error"
try:
value = response.json()
candidate = value.get("error", {}).get("code")
if candidate in SAFE_UPSTREAM_CODES:
code = candidate
except (requests.RequestException, ValueError, AttributeError):
return GatewayError(response.status_code, code)
return GatewayError(response.status_code, code)
class GatewayServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
block_on_close = False
def __init__(
self,
address,
provider,
key,
max_concurrent=MAX_CONCURRENT,
max_connections=MAX_CONNECTIONS,
):
self.provider = provider
self.gateway_key = key
self.capacity = threading.BoundedSemaphore(max_concurrent)
self.connection_capacity = threading.BoundedSemaphore(max_connections)
super().__init__(address, GatewayHandler)
def get_request(self):
request, address = super().get_request()
request.settimeout(HEADER_TIMEOUT)
return request, address
def process_request(self, request, client_address):
if not self.connection_capacity.acquire(blocking=False):
self.shutdown_request(request)
return
try:
super().process_request(request, client_address)
except BaseException:
self.connection_capacity.release()
raise
def process_request_thread(self, request, client_address):
try:
super().process_request_thread(request, client_address)
finally:
self.connection_capacity.release()
def handle_error(self, request, client_address):
return
class GatewayHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, format, *args):
return
@property
def gateway(self):
return cast(GatewayServer, self.server)
def _authorized(self):
value = self.headers.get("Authorization", "")
prefix = "Bearer "
supplied = value[len(prefix) :] if value.startswith(prefix) else ""
return hmac.compare_digest(supplied.encode(), self.gateway.gateway_key.encode())
def _json(self, status, value):
body = json.dumps(value, separators=(",", ":")).encode()
try:
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self.send_header("Connection", "close")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
self.close_connection = True
except OSError:
return
def _error(self, error):
self.close_connection = True
self._json(error.status, {"error": {"message": "Gateway request failed.", "type": "gateway_error", "code": error.code}})
def _enter(self):
if not self.gateway.capacity.acquire(blocking=False):
self._error(GatewayError(503, "gateway_busy"))
return False
return True
def do_GET(self):
self.connection.settimeout(SOCKET_TIMEOUT)
if not self._enter():
return
try:
target = urlsplit(self.path)
if target.query or target.fragment:
self._error(GatewayError(404, "not_found"))
return
path = target.path
if path == "/healthz":
self._json(200, {"status": "ready"})
return
if not self._authorized():
self._error(GatewayError(401, "unauthorized"))
return
if path != "/v1/models":
self._error(GatewayError(404, "not_found"))
return
data = [{"id": slug, "object": "model", "created": 0, "owned_by": "openai"} for slug, _name in self.gateway.provider.models()]
self._json(200, {"object": "list", "data": data})
except GatewayError as error:
self._error(error)
except (auth.AppError, OSError):
self._error(GatewayError(503, "credentials_unavailable"))
finally:
self.gateway.capacity.release()
def do_POST(self):
self.connection.settimeout(SOCKET_TIMEOUT)
if not self._enter():
return
upstream = None
try:
if not self._authorized():
raise GatewayError(401, "unauthorized")
target = urlsplit(self.path)
if target.path != "/v1/responses" or target.query or target.fragment:
raise GatewayError(404, "not_found")
if self.headers.get("Transfer-Encoding") is not None:
raise GatewayError(400, "unsupported_transfer_encoding")
content_type = self.headers.get("Content-Type", "").lower().replace(" ", "")
if content_type not in {"application/json", "application/json;charset=utf-8"}:
raise GatewayError(415, "unsupported_content_type")
lengths = self.headers.get_all("Content-Length", [])
if len(lengths) != 1:
raise GatewayError(400, "invalid_content_length")
raw_length = lengths[0]
try:
length = int(raw_length) if raw_length is not None else -1
except ValueError:
length = -1
if length < 0:
raise GatewayError(411, "content_length_required")
if length > MAX_BODY:
raise GatewayError(413, "request_too_large")
try:
value = json.loads(self.rfile.read(length))
except (ValueError, UnicodeError):
raise GatewayError(400, "invalid_json") from None
eligible = {slug for slug, _name in self.gateway.provider.models()}
body = normalize_request(value, eligible)
wants_stream = value.get("stream") is True
upstream = self.gateway.provider.response(body)
if upstream.is_redirect or upstream.status_code != 200:
raise _upstream_error(upstream)
media_type = upstream.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
if media_type and media_type != "text/event-stream":
raise GatewayError(502, "upstream_content_type_invalid")
if wants_stream:
self._stream(upstream)
else:
self._aggregate(upstream)
except GatewayError as error:
self._error(error)
except (auth.AppError, OSError):
self._error(GatewayError(503, "credentials_unavailable"))
finally:
if upstream is not None:
upstream.close()
self.gateway.capacity.release()
def _stream(self, upstream):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-store")
self.send_header("Connection", "close")
self.end_headers()
terminal = False
try:
for raw, event in _events(upstream):
self.wfile.write(raw)
self.wfile.flush()
if event and event["type"] in {"response.completed", "response.failed", "response.incomplete", "error"}:
terminal = True
if not terminal:
raise GatewayError(502, "upstream_stream_interrupted")
except (GatewayError, OSError):
if not terminal:
safe = b'event: error\ndata: {"type":"error","code":"upstream_stream_interrupted","message":"Gateway stream interrupted."}\n\n'
try:
self.wfile.write(safe)
self.wfile.flush()
except OSError:
return
finally:
self.close_connection = True
def _aggregate(self, upstream):
completed = None
terminal_error = None
output_items = {}
for _raw, event in _events(upstream):
if event is None:
continue
if event["type"] == "response.output_item.done":
index = event.get("output_index")
item = event.get("item")
if isinstance(index, int) and not isinstance(index, bool) and 0 <= index < 1024 and isinstance(item, dict):
output_items[index] = item
else:
terminal_error = "upstream_response_invalid"
elif event["type"] == "response.completed":
response = event.get("response")
if isinstance(response, dict) and response.get("status") == "completed" and isinstance(response.get("output"), list):
completed = response
else:
terminal_error = "upstream_response_invalid"
elif event["type"] in {"response.failed", "response.incomplete", "error"}:
terminal_error = "upstream_response_failed"
if terminal_error or completed is None:
raise GatewayError(502, terminal_error or "upstream_stream_interrupted")
if not completed["output"] and output_items:
completed = {**completed, "output": [output_items[index] for index in sorted(output_items)]}
self._json(200, completed)
def serve(args):
key = read_gateway_key(args.gateway_key_file)
provider = Provider(args.state_dir)
provider.ready()
server = GatewayServer((args.host, args.port), provider, key)
try:
server.serve_forever(poll_interval=0.25)
finally:
server.server_close()