Files

946 lines
34 KiB
Python

"""HTTP API для Xenith Studio — только стандартная библиотека Python.
Сервер предназначен для локального использования и будущего мобильного
приложения. Он не знает ничего о UI: вся работа с моделью выполняется через
переданные callable-объекты.
Маршруты:
GET /health — проверка доступности (без токена);
GET /v1/models — список моделей в формате OpenAI;
POST /v1/chat/completions — чат в формате OpenAI (обычный и SSE-стрим);
GET /api/tags — список моделей в формате Ollama;
POST /api/chat — чат в формате Ollama (обычный и NDJSON-стрим).
Особенности:
* Bearer-токен (или ?token=) для всех маршрутов, кроме /health;
* CORS для запросов из другого origin (например, из WebView телефона);
* ограничение тела запроса 2 МБ;
* один общий lock на вызовы модели — локальный движок не любит
параллельную генерацию.
"""
from __future__ import annotations
import json
import queue
import secrets
import threading
import time
import traceback
import uuid
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Callable, Optional
from urllib.parse import parse_qs, urlparse
__all__ = ["ApiServer", "parse_messages"]
MAX_BODY_BYTES = 2 * 1024 * 1024
MAX_LOG_LINES = 300
DEFAULT_MODEL = "xenith"
CORS_ALLOW_HEADERS = "Authorization, Content-Type, Accept, Origin, X-Requested-With"
ChatCallable = Callable[
[list[dict[str, Any]], dict[str, Any], Optional[Callable[[str], None]]],
str,
]
ModelsCallable = Callable[[], list[dict[str, Any]]]
# ---------------------------------------------------------------------------
# Нормализация сообщений
# ---------------------------------------------------------------------------
def _content_to_text(content: Any) -> str:
"""Приводит content (строка / список частей / объект) к обычному тексту."""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
return "".join(_content_to_text(part) for part in content)
if isinstance(content, dict):
# OpenAI: {"type": "text", "text": "..."}
# Некоторые клиенты присылают {"content": "..."}.
for key in ("text", "content"):
if key in content:
return _content_to_text(content[key])
return ""
return str(content)
def parse_messages(messages: Any) -> list[dict[str, str]]:
"""Нормализует сообщения OpenAI/Ollama в [{"role": ..., "content": ...}].
Поддерживаются:
* строка вместо массива сообщений;
* content-строка;
* content-массив текстовых частей (multimodal-формат OpenAI).
Нетекстовые части (например, image_url) пропускаются — движок текстовый.
"""
if messages is None:
return []
if isinstance(messages, str):
return [{"role": "user", "content": messages}]
if not isinstance(messages, list):
raise ValueError("messages должен быть массивом сообщений")
result: list[dict[str, str]] = []
for item in messages:
if isinstance(item, str):
result.append({"role": "user", "content": item})
continue
if not isinstance(item, dict):
continue
role = str(item.get("role") or "user").strip().lower() or "user"
result.append(
{
"role": role,
"content": _content_to_text(item.get("content")),
}
)
return result
# ---------------------------------------------------------------------------
# Вспомогательные функции
# ---------------------------------------------------------------------------
def _normalize_path(path: str) -> str:
"""Убирает завершающие слеши, кроме корневого."""
path = path or "/"
if len(path) > 1:
path = path.rstrip("/")
return path or "/"
def _as_float(value: Any, default: float) -> float:
try:
if value is None:
return default
return float(value)
except (TypeError, ValueError):
return default
def _as_int(value: Any, default: int) -> int:
try:
if value is None:
return default
return int(value)
except (TypeError, ValueError):
return default
def _lookup(sources: tuple[Any, ...], keys: tuple[str, ...], default: Any = None) -> Any:
for source in sources:
if not isinstance(source, dict):
continue
for key in keys:
value = source.get(key)
if value is not None:
return value
return default
def _build_params(
body: dict[str, Any],
options: Any = None,
*,
stream: bool = False,
) -> dict[str, Any]:
"""Собирает params для chat_callable из OpenAI- или Ollama-запроса."""
opts = options if isinstance(options, dict) else {}
sources = (body, opts)
temperature = _as_float(_lookup(sources, ("temperature",), 0.7), 0.7)
top_p = _as_float(_lookup(sources, ("top_p",), 0.9), 0.9)
max_tokens = _as_int(
_lookup(sources, ("max_tokens", "max_completion_tokens", "num_predict"), 256),
256,
)
# Держим значения в разумных пределах, чтобы не сломать движок.
temperature = max(0.0, min(temperature, 5.0))
top_p = max(0.0, min(top_p, 1.0))
max_tokens = max(1, min(max_tokens, 32768))
return {
"temperature": temperature,
"top_p": top_p,
"max_tokens": max_tokens,
"n": max_tokens, # совместимость с XenithEngine
"stream": bool(stream),
}
def _utc_now() -> str:
"""Время в формате Ollama, например 2026-11-22T12:00:00Z."""
return (
datetime.now(timezone.utc)
.isoformat(timespec="seconds")
.replace("+00:00", "Z")
)
class _ApiError(Exception):
"""Ошибка запроса с HTTP-статусом (обрабатывается в do_POST/do_GET)."""
def __init__(self, status: int, message: str) -> None:
super().__init__(message)
self.status = status
def _result_text(result: Any, collected: list[str]) -> str:
"""Возвращает текст ответа, даже если движок отдал его только через on_token."""
if isinstance(result, str):
text = result
elif result is None:
text = ""
else:
text = str(result)
return text or "".join(collected)
# ---------------------------------------------------------------------------
# Сервер
# ---------------------------------------------------------------------------
class ApiServer:
"""Потоковый HTTP API-сервер Xenith.
chat_callable(messages, params, on_token) -> str
Синхронный вызов модели. Может занимать секунды, вызывается из
отдельного потока запроса. on_token(piece) можно вызывать много раз.
models_callable() -> list[dict]
Список моделей; у элементов должны быть поля id и name.
"""
def __init__(
self,
chat_callable: ChatCallable,
models_callable: ModelsCallable,
host: str = "127.0.0.1",
port: int = 1234,
token: str = "",
cors: bool = True,
) -> None:
if not callable(chat_callable):
raise TypeError("chat_callable должен быть вызываемым")
if not callable(models_callable):
raise TypeError("models_callable должен быть вызываемым")
self.chat_callable = chat_callable
self.models_callable = models_callable
self.host = str(host)
self.port = int(port)
self.token = str(token or "")
self.cors = bool(cors)
self.engine_name = "xenith"
# Последние строки лога (не более MAX_LOG_LINES) и необязательный callback.
self.log: list[str] = []
self.log_callback: Optional[Callable[[str], None]] = None
self._state_lock = threading.Lock()
self._log_lock = threading.Lock()
self._chat_lock = threading.Lock()
self._server: Optional[_ApiHTTPServer] = None
self._thread: Optional[threading.Thread] = None
# -- состояние ---------------------------------------------------------
@property
def is_running(self) -> bool:
thread = self._thread
return bool(thread is not None and thread.is_alive())
@property
def address(self) -> str:
host = self.host
if ":" in host and not host.startswith("["):
host = f"[{host}]" # IPv6
return f"{host}:{self.port}"
def _emit_log(self, message: str) -> None:
line = f"{time.strftime('%H:%M:%S')} {message}"
with self._log_lock:
self.log.append(line)
if len(self.log) > MAX_LOG_LINES:
del self.log[: len(self.log) - MAX_LOG_LINES]
callback = self.log_callback
if callback is not None:
try:
callback(line)
except Exception:
# Ошибка в пользовательском логгере не должна ронять сервер.
pass
def start(self) -> None:
"""Запускает сервер в фоновом потоке. Не блокирует вызывающий код."""
with self._state_lock:
if self.is_running:
self._emit_log("API-сервер уже запущен")
return
try:
httpd = _ApiHTTPServer((self.host, self.port), _ApiHandler)
except OSError as exc:
raise RuntimeError(
f"Не удалось запустить API-сервер на {self.host}:{self.port}: "
f"порт занят или недоступен ({exc})"
) from exc
httpd.api = self
httpd.daemon_threads = True
httpd.allow_reuse_address = True
self._server = httpd
# Если был запрошен port=0, узнаём реальный порт.
self.port = int(httpd.server_address[1])
self._thread = threading.Thread(
target=httpd.serve_forever,
kwargs={"poll_interval": 0.2},
name="xenith-api",
daemon=True,
)
self._thread.start()
address = self.address
self._emit_log(f"API-сервер запущен: http://{address}")
if not self.token and self.host not in ("127.0.0.1", "localhost", "::1"):
self._emit_log("Внимание: API доступен без токена не только с localhost")
def stop(self) -> None:
"""Корректно останавливает сервер и ждёт завершения его потока."""
with self._state_lock:
httpd = self._server
thread = self._thread
self._server = None
self._thread = None
if httpd is None:
return
self._emit_log("Остановка API-сервера...")
try:
httpd.shutdown()
except Exception as exc:
self._emit_log(f"shutdown: {exc}")
try:
httpd.server_close()
except Exception as exc:
self._emit_log(f"server_close: {exc}")
if thread is not None and thread is not threading.current_thread():
thread.join(timeout=5.0)
if thread.is_alive():
self._emit_log("Поток API-сервера не завершился за 5 секунд")
self._emit_log("API-сервер остановлен")
# -- данные для маршрутов ---------------------------------------------
def _load_models(self) -> list[dict[str, str]]:
try:
raw = self.models_callable()
except Exception as exc:
self._emit_log(f"models_callable: {exc}")
return []
if not isinstance(raw, list):
return []
result: list[dict[str, str]] = []
for item in raw:
if isinstance(item, str):
model_id = name = item.strip()
elif isinstance(item, dict):
model_id = str(item.get("id") or item.get("name") or "").strip()
name = str(item.get("name") or model_id).strip()
else:
continue
if model_id:
result.append({"id": model_id, "name": name or model_id})
return result
def default_model(self) -> str:
models = self._load_models()
return models[0]["id"] if models else DEFAULT_MODEL
def _is_authorized(self, headers: Any, query: dict[str, list[str]]) -> bool:
if not self.token:
return True
supplied = ""
authorization = headers.get("Authorization") or ""
parts = authorization.split(None, 1)
if len(parts) == 2 and parts[0].lower() == "bearer":
supplied = parts[1].strip()
elif authorization:
supplied = authorization.strip()
# Совместимость: ?token=... (удобно для простых клиентов/WebView).
if not supplied:
values = query.get("token") or []
if values:
supplied = str(values[0])
return secrets.compare_digest(
supplied.encode("utf-8"),
self.token.encode("utf-8"),
)
# ---------------------------------------------------------------------------
# HTTP-сервер и обработчик
# ---------------------------------------------------------------------------
class _ApiHTTPServer(ThreadingHTTPServer):
daemon_threads = True
allow_reuse_address = True
request_queue_size = 64
api: "ApiServer"
class _ApiHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server_version = "XenithAPI/1.0"
sys_version = ""
timeout = 60 # не держим «зависшие» соединения вечно
_headers_sent = False
_disconnect_logged = False
# -- инфраструктура ----------------------------------------------------
@property
def api(self) -> ApiServer:
return self.server.api # type: ignore[attr-defined]
def setup(self) -> None:
super().setup()
self._headers_sent = False
self._disconnect_logged = False
def handle_one_request(self) -> None:
# Флаги сбрасываются на каждый запрос при keep-alive.
self._headers_sent = False
self._disconnect_logged = False
super().handle_one_request()
def finish(self) -> None:
try:
super().finish()
except OSError:
# Клиент мог закрыть соединение раньше нас — это нормально.
self.close_connection = True
def log_message(self, format: str, *args: Any) -> None:
try:
self.api._emit_log(f"{self.client_address[0]} — {format % args}")
except Exception:
pass
def _send_cors(self, allow_headers: Optional[str] = None) -> None:
if not getattr(self.api, "cors", True):
return
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header(
"Access-Control-Allow-Headers",
allow_headers or CORS_ALLOW_HEADERS,
)
self.send_header("Access-Control-Expose-Headers", "Content-Type")
def _send_json(
self,
status: int,
payload: Any,
*,
extra_headers: Optional[dict[str, str]] = None,
) -> None:
if self._headers_sent:
return
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self._send_cors()
if extra_headers:
for key, value in extra_headers.items():
self.send_header(key, value)
if self.close_connection:
self.send_header("Connection", "close")
self.end_headers()
self._headers_sent = True
try:
self.wfile.write(body)
self.wfile.flush()
except OSError:
self.close_connection = True
def _send_error_json(
self,
status: int,
message: str,
*,
ollama: bool = False,
extra_headers: Optional[dict[str, str]] = None,
) -> None:
self.api._emit_log(f"Ошибка {status}: {message}")
if ollama:
# Ollama-клиенты ожидают error строкой.
payload: Any = {"error": message}
else:
payload = {
"error": {
"message": message,
"type": "invalid_request_error" if status < 500 else "server_error",
"code": status,
}
}
self._send_json(status, payload, extra_headers=extra_headers)
def _log_disconnect(self, exc: BaseException) -> None:
self.close_connection = True
if self._disconnect_logged:
return
self._disconnect_logged = True
self.api._emit_log(f"Клиент отключился во время потоковой передачи: {exc}")
def _write_sse(self, payload: Optional[dict[str, Any]]) -> bool:
"""Пишет SSE-событие. Возвращает False, если клиент отключился."""
if payload is None:
raw = b"data: [DONE]\n\n"
else:
raw = (
"data: "
+ json.dumps(payload, ensure_ascii=False)
+ "\n\n"
).encode("utf-8")
try:
self.wfile.write(raw)
self.wfile.flush()
return True
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError) as exc:
# BrokenPipeError/ConnectionResetError — штатный уход клиента.
self._log_disconnect(exc)
return False
def _write_ndjson(self, payload: dict[str, Any]) -> bool:
raw = (json.dumps(payload, ensure_ascii=False) + "\n").encode("utf-8")
try:
self.wfile.write(raw)
self.wfile.flush()
return True
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError) as exc:
self._log_disconnect(exc)
return False
# -- чтение и проверка запроса ----------------------------------------
def _check_auth(self, parsed: Any) -> bool:
query = parse_qs(parsed.query)
if self.api._is_authorized(self.headers, query):
return True
# Тело POST не читаем — соединение нужно закрыть, иначе остаток тела
# будет воспринят как следующий HTTP-запрос.
if self.command == "POST":
self.close_connection = True
self._send_error_json(
401,
"Неверный или отсутствующий токен",
extra_headers={"WWW-Authenticate": "Bearer"},
)
return False
def _read_json(self) -> dict[str, Any]:
transfer_encoding = (self.headers.get("Transfer-Encoding") or "").lower()
if "chunked" in transfer_encoding:
self.close_connection = True
raise _ApiError(400, "Chunked-запросы не поддерживаются, укажите Content-Length")
raw_length = self.headers.get("Content-Length")
if raw_length is None or not raw_length.strip():
return {}
try:
length = int(raw_length)
except ValueError:
self.close_connection = True
raise _ApiError(400, "Некорректный заголовок Content-Length") from None
if length < 0:
self.close_connection = True
raise _ApiError(400, "Content-Length не может быть отрицательным")
if length > MAX_BODY_BYTES:
self.close_connection = True
raise _ApiError(
413,
f"Тело запроса больше {MAX_BODY_BYTES // (1024 * 1024)} МБ",
)
if length == 0:
return {}
raw = self.rfile.read(length)
if len(raw) != length:
self.close_connection = True
raise _ApiError(400, "Не удалось прочитать тело запроса целиком")
try:
text = raw.decode("utf-8")
except UnicodeDecodeError as exc:
raise _ApiError(400, f"Тело запроса не в UTF-8: {exc}") from None
try:
payload = json.loads(text)
except json.JSONDecodeError as exc:
raise _ApiError(
400,
f"Некорректный JSON: {exc.msg} (строка {exc.lineno})",
) from None
if not isinstance(payload, dict):
raise _ApiError(400, "Тело запроса должно быть JSON-объектом")
return payload
def _prepare_chat(
self,
*,
default_stream: bool,
) -> tuple[list[dict[str, Any]], dict[str, Any], str, bool, dict[str, Any]]:
body = self._read_json()
raw_messages = body.get("messages")
if not isinstance(raw_messages, list) or not raw_messages:
raise _ApiError(400, "Поле messages обязательно и должно быть непустым массивом")
try:
messages = parse_messages(raw_messages)
except ValueError as exc:
raise _ApiError(400, str(exc)) from None
if not messages:
raise _ApiError(400, "После нормализации не осталось ни одного сообщения")
stream = bool(body.get("stream", default_stream))
model = str(body.get("model") or "").strip() or self.api.default_model()
options = body.get("options")
params = _build_params(
body,
options if isinstance(options, dict) else None,
stream=stream,
)
return messages, params, model, stream, body
def _collect_chat(
self,
messages: list[dict[str, Any]],
params: dict[str, Any],
) -> str:
collected: list[str] = []
def on_token(piece: str) -> None:
if piece:
collected.append(str(piece))
with self.api._chat_lock:
result = self.api.chat_callable(messages, params, on_token)
return _result_text(result, collected)
def _start_chat_events(
self,
messages: list[dict[str, Any]],
params: dict[str, Any],
) -> "queue.Queue[tuple[str, str]]":
"""Запускает chat_callable в отдельном потоке и отдаёт очередь событий.
События: ("token", piece), ("done", ""), ("error", message).
Очередь не ограничена, поэтому медленный/отключившийся клиент не
блокирует поток модели.
"""
events: "queue.Queue[tuple[str, str]]" = queue.Queue()
def worker() -> None:
emitted = False
def on_token(piece: str) -> None:
nonlocal emitted
if not piece:
return
emitted = True
events.put(("token", str(piece)))
try:
with self.api._chat_lock:
result = self.api.chat_callable(messages, params, on_token)
text = "" if result is None else (result if isinstance(result, str) else str(result))
if not emitted and text:
# Движок не умеет стримить — отдаём весь ответ одним куском.
events.put(("token", text))
events.put(("done", ""))
except Exception as exc:
self.api._emit_log(f"Ошибка chat_callable: {exc}")
self.api._emit_log(traceback.format_exc().strip())
events.put(("error", str(exc)))
threading.Thread(
target=worker,
name="xenith-api-chat",
daemon=True,
).start()
return events
# -- GET ---------------------------------------------------------------
def do_GET(self) -> None:
parsed = urlparse(self.path)
path = _normalize_path(parsed.path)
# /health доступен без токена: удобно для проверки «жив ли сервер».
if path == "/health":
self._send_json(
200,
{
"status": "ok",
"engine": self.api.engine_name,
"auth_required": bool(self.api.token),
},
)
return
if not self._check_auth(parsed):
return
try:
if path == "/v1/models":
models = self.api._load_models()
self._send_json(
200,
{
"object": "list",
"data": [
{
"id": model["id"],
"object": "model",
"owned_by": "xenith",
}
for model in models
],
},
)
elif path == "/api/tags":
models = self.api._load_models()
self._send_json(
200,
{
"models": [
{"name": model["id"], "model": model["id"]}
for model in models
]
},
)
else:
self.close_connection = True
self._send_error_json(404, f"Маршрут не найден: {path}")
except Exception as exc:
self.api._emit_log(f"Ошибка GET {path}: {exc}")
self._send_error_json(500, str(exc))
# -- POST --------------------------------------------------------------
def do_POST(self) -> None:
parsed = urlparse(self.path)
path = _normalize_path(parsed.path)
if not self._check_auth(parsed):
return
try:
if path == "/v1/chat/completions":
self._handle_openai_chat()
elif path == "/api/chat":
self._handle_ollama_chat()
else:
# Тело неизвестного маршрута не читаем — закрываем соединение.
self.close_connection = True
self._send_error_json(404, f"Маршрут не найден: {path}")
except _ApiError as exc:
self._send_error_json(
exc.status,
str(exc),
ollama=(path == "/api/chat"),
)
except (BrokenPipeError, ConnectionResetError):
self.close_connection = True
self.api._emit_log("Соединение с клиентом потеряно")
except Exception as exc:
# Любая ошибка модели/обработки — JSON 500, сервер продолжает жить.
self.api._emit_log(f"Необработанная ошибка POST {path}: {exc}")
self.api._emit_log(traceback.format_exc().strip())
self._send_error_json(500, str(exc), ollama=(path == "/api/chat"))
def _handle_openai_chat(self) -> None:
messages, params, model, stream, _body = self._prepare_chat(default_stream=False)
if stream:
self._stream_openai(messages, params, model)
return
text = self._collect_chat(messages, params)
completion_id = f"chatcmpl-{uuid.uuid4().hex}"
self._send_json(
200,
{
"id": completion_id,
"object": "chat.completion",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": text},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
},
},
)
def _stream_openai(
self,
messages: list[dict[str, Any]],
params: dict[str, Any],
model: str,
) -> None:
completion_id = f"chatcmpl-{uuid.uuid4().hex}"
created = int(time.time())
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_cors()
self.send_header("Connection", "close")
self.end_headers()
self._headers_sent = True
self.close_connection = True
def chunk(delta: dict[str, Any], finish_reason: Optional[str] = None) -> dict[str, Any]:
return {
"id": completion_id,
"object": "chat.completion.chunk",
"created": created,
"model": model,
"choices": [
{
"index": 0,
"delta": delta,
"finish_reason": finish_reason,
}
],
}
# Первый чанк — роль, как в OpenAI.
if not self._write_sse(chunk({"role": "assistant", "content": ""})):
return
events = self._start_chat_events(messages, params)
while True:
kind, value = events.get()
if kind == "token":
if not self._write_sse(chunk({"content": value})):
return
elif kind == "error":
if self._write_sse(
{"error": {"message": value, "type": "server_error"}}
):
self._write_sse(None)
return
else: # done
if self._write_sse(chunk({}, "stop")):
self._write_sse(None)
return
def _handle_ollama_chat(self) -> None:
# Ollama по умолчанию стримит, поэтому default_stream=True.
messages, params, model, stream, _body = self._prepare_chat(default_stream=True)
if stream:
self._stream_ollama(messages, params, model)
return
text = self._collect_chat(messages, params)
self._send_json(
200,
{
"model": model,
"created_at": _utc_now(),
"message": {"role": "assistant", "content": text},
"done": True,
},
)
def _stream_ollama(
self,
messages: list[dict[str, Any]],
params: dict[str, Any],
model: str,
) -> None:
created_at = _utc_now()
self.send_response(200)
self.send_header("Content-Type", "application/x-ndjson")
self.send_header("Cache-Control", "no-cache")
self.send_header("X-Accel-Buffering", "no")
self._send_cors()
self.send_header("Connection", "close")
self.end_headers()
self._headers_sent = True
self.close_connection = True
def line(content: str, done: bool) -> dict[str, Any]:
return {
"model": model,
"created_at": created_at,
"message": {"role": "assistant", "content": content},
"done": done,
}
events = self._start_chat_events(messages, params)
while True:
kind, value = events.get()
if kind == "token":
if not self._write_ndjson(line(value, False)):
return
elif kind == "error":
# Формат ошибки Ollama: одна JSON-строка с полем error.
self._write_ndjson({"error": value, "done": True})
return
else: # done
self._write_ndjson(line("", True))
return
# -- OPTIONS (CORS preflight) -----------------------------------------
def do_OPTIONS(self) -> None:
# Preflight не содержит Authorization, поэтому токен здесь не проверяем.
requested = self.headers.get("Access-Control-Request-Headers")
self.send_response(204)
self._send_cors(requested or CORS_ALLOW_HEADERS)
self.send_header("Access-Control-Max-Age", "86400")
self.send_header("Content-Length", "0")
self.end_headers()