493 lines
25 KiB
Python
493 lines
25 KiB
Python
"""Шлюз к модели (T2): одна дверь к провайдерам для программы на машине человека.
|
||
|
||
Клиент знает только этот адрес и псевдоним модели; ключи провайдеров остаются на
|
||
сервере. Расход привязан ровно к одному месту — проверке (X-Review-Id) или диалогу
|
||
(X-Tab-Id); пределы проверяются ДО вызова провайдера, на вызов ставится бронь,
|
||
а строка расхода заводится заготовкой и закрывается фактическими числами. Обрыв
|
||
потока и гибель процесса не делают расход бесплатным: бронь остаётся в строке.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import json
|
||
import logging
|
||
import os
|
||
import threading
|
||
import time
|
||
|
||
from fastapi import HTTPException, Request
|
||
from fastapi.responses import JSONResponse, StreamingResponse
|
||
|
||
import contract_errors
|
||
|
||
import db
|
||
|
||
_log = logging.getLogger("smeta_web.gateway")
|
||
|
||
RESERVE_RUB = float(os.environ.get("GATEWAY_RESERVE_RUB", "1.0"))
|
||
CALL_TIMEOUT_SEC = float(os.environ.get("GATEWAY_TIMEOUT_SEC", "120"))
|
||
|
||
_lock = threading.RLock() # _admit зовёт _reserve под тем же замком
|
||
_inflight_user: dict[str, int] = {}
|
||
_inflight_review: dict[int, int] = {}
|
||
|
||
|
||
def _reserve(username: str, review_id: int | None) -> None:
|
||
with _lock:
|
||
_inflight_user[username] = _inflight_user.get(username, 0) + 1
|
||
if review_id is not None:
|
||
_inflight_review[review_id] = _inflight_review.get(review_id, 0) + 1
|
||
|
||
|
||
def _release(username: str, review_id: int | None) -> None:
|
||
with _lock:
|
||
if _inflight_user.get(username):
|
||
_inflight_user[username] -= 1
|
||
if not _inflight_user[username]:
|
||
_inflight_user.pop(username, None)
|
||
if review_id is not None and _inflight_review.get(review_id):
|
||
_inflight_review[review_id] -= 1
|
||
if not _inflight_review[review_id]:
|
||
_inflight_review.pop(review_id, None)
|
||
|
||
|
||
def _inflight(username: str, review_id: int | None) -> tuple[int, int]:
|
||
with _lock:
|
||
return (_inflight_user.get(username, 0),
|
||
_inflight_review.get(review_id, 0) if review_id is not None else 0)
|
||
|
||
|
||
def _openai_sse(text: str) -> str:
|
||
chunk = {"choices": [{"delta": {"content": text}, "index": 0}]}
|
||
return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
||
|
||
|
||
class ProviderError(RuntimeError):
|
||
"""Отказ провайдера со статусом — чтобы код отказа был машинным, а не разбором текста.
|
||
|
||
Живой случай 19.11.2026: провайдер ответил 429 (пятичасовой предел подписки), а клиент
|
||
показывал «квоту», разбирая «429» из текста сообщения. Теперь статус едет отдельно.
|
||
"""
|
||
|
||
def __init__(self, status: int, text: str):
|
||
super().__init__(f"провайдер ответил {status}: {text}")
|
||
self.status = status
|
||
|
||
|
||
def _fail(request, status: int, code: str, body: dict):
|
||
"""R-01: отказ шлюза сохраняет старые поля и добавляет машинный код и номер запроса."""
|
||
out = dict(body)
|
||
out["code"] = code
|
||
out["request_id"] = getattr(request.state, "request_id", "")
|
||
return JSONResponse(status_code=status, content=out)
|
||
|
||
|
||
def _openai_tool_sse(call: dict) -> str:
|
||
"""Кусок вызова инструмента в виде OpenAI: имя и id — первым куском, дальше аргументы."""
|
||
tc: dict = {"index": call.get("index", 0)}
|
||
if call.get("id") is not None:
|
||
tc["id"] = call["id"]
|
||
if call.get("name"):
|
||
tc["type"] = "function"
|
||
tc["function"] = {"name": call["name"], "arguments": call.get("arguments") or ""}
|
||
else:
|
||
tc["function"] = {"arguments": call.get("arguments") or ""}
|
||
chunk = {"choices": [{"delta": {"tool_calls": [tc]}, "index": 0}]}
|
||
return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
||
|
||
|
||
def _openai_finish_sse(reason: str) -> str:
|
||
chunk = {"choices": [{"delta": {}, "finish_reason": reason, "index": 0}]}
|
||
return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
||
|
||
|
||
def _stream_state() -> dict:
|
||
# tool_calls — счётчик ВЫЗОВОВ в форме OpenAI: индекс блока провайдера не годится,
|
||
# текст перед инструментом сдвигает его, и клиент получил бы пропуск в нумерации.
|
||
return {"usage": {}, "tool_calls": 0, "blocks": {}}
|
||
|
||
|
||
def _event_to_events(ev: dict, state: dict) -> list[dict]:
|
||
"""Событие потока провайдера → события шлюза. Инструменты переводятся в tool_calls."""
|
||
kind = ev.get("type")
|
||
if kind == "error":
|
||
detail = (ev.get("error") or {}).get("message") or "провайдер вернул ошибку"
|
||
raise RuntimeError(str(detail))
|
||
out: list[dict] = []
|
||
if kind == "content_block_start":
|
||
block = ev.get("content_block") or {}
|
||
if block.get("type") == "tool_use":
|
||
index = state["tool_calls"]
|
||
state["tool_calls"] += 1
|
||
state.setdefault("blocks", {})[ev.get("index", 0)] = index
|
||
out.append({"tool_call": {"index": index, "id": block.get("id"),
|
||
"name": block.get("name"), "arguments": ""}})
|
||
elif kind == "content_block_delta":
|
||
delta = ev.get("delta") or {}
|
||
if delta.get("type") == "input_json_delta" and delta.get("partial_json"):
|
||
block_index = ev.get("index", 0)
|
||
out.append({"tool_call": {"index": state["blocks"].get(block_index, 0),
|
||
"arguments": delta["partial_json"]}})
|
||
elif delta.get("text"):
|
||
out.append({"delta": delta["text"]})
|
||
elif kind == "message_start":
|
||
u = (ev.get("message") or {}).get("usage") or {}
|
||
state["usage"]["input_tokens"] = u.get("input_tokens")
|
||
state["usage"]["cache_read_input_tokens"] = u.get("cache_read_input_tokens")
|
||
state["usage"]["cache_creation_input_tokens"] = u.get("cache_creation_input_tokens")
|
||
elif kind == "message_delta":
|
||
u = ev.get("usage") or {}
|
||
if "output_tokens" in u:
|
||
state["usage"]["output_tokens"] = u["output_tokens"]
|
||
stop = (ev.get("delta") or {}).get("stop_reason")
|
||
if stop:
|
||
# OpenAI-смысл: обрезанный по пределу ответ — length, а не «закончен».
|
||
finish = {"tool_use": "tool_calls", "max_tokens": "length"}.get(stop, "stop")
|
||
out.append({"finish": finish})
|
||
return out
|
||
|
||
|
||
def _line_to_events(line: str, state: dict) -> list[dict]:
|
||
"""Строка SSE провайдера → события шлюза (общий путь для боя и проверок)."""
|
||
if not line.startswith("data:"):
|
||
return []
|
||
try:
|
||
ev = json.loads(line[5:].strip())
|
||
except ValueError:
|
||
return []
|
||
return _event_to_events(ev, state)
|
||
|
||
|
||
ROLE_MAP = {"system": "system", "developer": "system", "user": "user",
|
||
"assistant": "assistant", "tool": "tool"}
|
||
|
||
|
||
def _to_provider(body: dict, model: str, cap: int) -> dict:
|
||
"""Запрос клиента (OpenAI-вид) → тело Messages API: system, сообщения, инструменты."""
|
||
raw = body.get("messages") or []
|
||
system_parts: list[str] = []
|
||
messages: list[dict] = []
|
||
pending_results: list[dict] = []
|
||
|
||
def flush_results() -> None:
|
||
# nonlocal обязателен: clear() на том же списке опустошил бы уже добавленное
|
||
nonlocal pending_results
|
||
if pending_results:
|
||
messages.append({"role": "user", "content": pending_results})
|
||
pending_results = []
|
||
|
||
for m in raw:
|
||
role = ROLE_MAP.get(m.get("role"), m.get("role"))
|
||
content = m.get("content")
|
||
if role == "system":
|
||
if isinstance(content, str) and content:
|
||
system_parts.append(content)
|
||
elif isinstance(content, list):
|
||
parts = [b.get("text") for b in content
|
||
if isinstance(b, dict) and b.get("type") == "text" and b.get("text")]
|
||
if parts:
|
||
system_parts.append("\n\n".join(parts))
|
||
continue
|
||
if role == "tool":
|
||
pending_results.append({
|
||
"type": "tool_result", "tool_use_id": m.get("tool_call_id") or "",
|
||
"content": content if isinstance(content, str)
|
||
else json.dumps(content, ensure_ascii=False)})
|
||
continue
|
||
flush_results()
|
||
if role == "assistant":
|
||
blocks: list[dict] = []
|
||
if isinstance(content, str) and content:
|
||
blocks.append({"type": "text", "text": content})
|
||
elif isinstance(content, list):
|
||
blocks.extend(content)
|
||
for call in (m.get("tool_calls") or []):
|
||
fn = call.get("function") or {}
|
||
try:
|
||
args = json.loads(fn.get("arguments") or "{}")
|
||
except ValueError:
|
||
args = {"_raw": fn.get("arguments")}
|
||
blocks.append({"type": "tool_use", "id": call.get("id") or "",
|
||
"name": fn.get("name") or "", "input": args})
|
||
messages.append({"role": "assistant", "content": blocks or ""})
|
||
else:
|
||
messages.append({"role": "user", "content": content if content is not None else ""})
|
||
flush_results()
|
||
payload = {"model": model,
|
||
"max_tokens": min(int(body.get("max_tokens") or cap), cap),
|
||
"stream": True, "messages": messages}
|
||
if body.get("thinking") == {"type": "disabled"}:
|
||
payload["thinking"] = {"type": "disabled"}
|
||
if system_parts:
|
||
payload["system"] = "\n\n".join(system_parts)
|
||
tools = []
|
||
for t in (body.get("tools") or []):
|
||
if not isinstance(t, dict):
|
||
continue
|
||
fn = t.get("function")
|
||
if t.get("type") == "function" and fn:
|
||
tools.append({"name": fn.get("name"),
|
||
"description": fn.get("description") or "",
|
||
"input_schema": fn.get("parameters")
|
||
or {"type": "object", "properties": {}}})
|
||
if tools:
|
||
payload["tools"] = tools
|
||
choice = body.get("tool_choice")
|
||
if isinstance(choice, str) and choice in ("auto", "none", "required"):
|
||
payload["tool_choice"] = {"type": "any" if choice == "required" else choice}
|
||
elif isinstance(choice, dict) and choice.get("type") == "function":
|
||
name = (choice.get("function") or {}).get("name")
|
||
if name:
|
||
payload["tool_choice"] = {"type": "tool", "name": name}
|
||
return payload
|
||
|
||
|
||
async def _provider_stream(profile, body): # noqa: ANN001 — подменяется в проверках
|
||
"""Поток провайдера: события {"delta"/"tool_call"/"finish"} и последним {"usage": {...}}.
|
||
|
||
Провайдеры у нас Anthropic-совместимые (base URL и ключ лежат в settings-файле
|
||
профиля), поэтому запрос переводится из OpenAI-вида в Messages API.
|
||
"""
|
||
import httpx
|
||
settings = json.loads(open(profile.settings_path, encoding="utf-8").read())
|
||
env = settings.get("env") or {}
|
||
base = (env.get("ANTHROPIC_BASE_URL") or "").rstrip("/")
|
||
token = env.get("ANTHROPIC_AUTH_TOKEN") or env.get("ANTHROPIC_API_KEY")
|
||
if not base or not token:
|
||
raise RuntimeError("провайдер не настроен: нет адреса или ключа")
|
||
cap = int(os.environ.get("GATEWAY_MAX_TOKENS", "4096"))
|
||
payload = _to_provider(body, profile.model, cap)
|
||
state = _stream_state()
|
||
async with httpx.AsyncClient(timeout=None) as client:
|
||
async with client.stream("POST", base + "/v1/messages", json=payload,
|
||
headers={"Authorization": f"Bearer {token}",
|
||
"anthropic-version": "2023-06-01"}) as resp:
|
||
if resp.status_code >= 400:
|
||
text = (await resp.aread()).decode("utf-8", "replace")[:300]
|
||
raise ProviderError(resp.status_code, text)
|
||
async for line in resp.aiter_lines():
|
||
if not line.startswith("data:"):
|
||
continue
|
||
for out in _line_to_events(line, state):
|
||
yield out
|
||
yield {"usage": state["usage"]}
|
||
|
||
|
||
def _price(username: str, model: str | None, usage: dict, started: float) -> dict:
|
||
try:
|
||
import billing
|
||
priced = billing.price_run(usage, model or "", started, time.time(), username)
|
||
except Exception: # noqa: BLE001 — цена не должна ронять поток
|
||
_log.exception("gateway: не удалось посчитать цену")
|
||
return {"price_rub": None, "cost_rub": None, "cost_usd": None, "cost_basis": "unknown"}
|
||
return priced
|
||
|
||
|
||
async def _pump(username: str, review_id: int | None, profile, body: dict,
|
||
usage_id: int, model: str | None, started: float,
|
||
queue: asyncio.Queue) -> None:
|
||
"""Читает провайдера до конца и закрывает строку. Отключение клиента не отменяет:
|
||
провайдер уже получил запрос, и его расход обязан остаться в учёте."""
|
||
usage: dict = {}
|
||
error: Exception | None = None
|
||
try:
|
||
async for ev in _provider_stream(profile, body):
|
||
if "usage" in ev:
|
||
usage = ev["usage"] or {}
|
||
else:
|
||
await queue.put(ev)
|
||
except asyncio.CancelledError:
|
||
error = RuntimeError("вызов отменён")
|
||
raise
|
||
except Exception as e: # noqa: BLE001 — обрыв провайдера: закрываем как «неизвестно»
|
||
error = e
|
||
_log.warning("gateway: провайдер оборвал поток: %s", e)
|
||
try:
|
||
await queue.put({"error": str(e) or type(e).__name__,
|
||
"code": "provider_quota"
|
||
if isinstance(e, ProviderError) and e.status == 429
|
||
else "provider_failed"})
|
||
except Exception: # noqa: BLE001 — очередь могла закрыться вместе с ответом
|
||
pass
|
||
finally:
|
||
try:
|
||
if error is not None and not usage:
|
||
await asyncio.to_thread(
|
||
db.settle_llm_usage_stub, usage_id, input_tokens=0, cache_tokens=0,
|
||
output_tokens=0, price_rub=RESERVE_RUB, cost_basis="unknown",
|
||
provider=profile.name, model=model)
|
||
if review_id is not None:
|
||
await asyncio.to_thread(db.add_cost, review_id, RESERVE_RUB)
|
||
else:
|
||
if "price_rub" in usage: # цена пришла от подменённого провайдера
|
||
priced = {"price_rub": usage.get("price_rub"), "cost_rub": None,
|
||
"cost_usd": None, "cost_basis": "usd"}
|
||
else:
|
||
priced = await asyncio.to_thread(_price, username, model, usage, started)
|
||
price = priced.get("price_rub")
|
||
await asyncio.to_thread(
|
||
db.settle_llm_usage_stub, usage_id,
|
||
input_tokens=(usage.get("input_tokens") or 0)
|
||
+ (usage.get("cache_creation_input_tokens") or 0),
|
||
cache_tokens=usage.get("cache_read_input_tokens"),
|
||
output_tokens=usage.get("output_tokens"),
|
||
price_rub=RESERVE_RUB if price is None else price,
|
||
cost_rub=priced.get("cost_rub"), cost_usd=priced.get("cost_usd"),
|
||
provider=profile.name, model=model,
|
||
cost_basis=priced.get("cost_basis") or ("unknown" if price is None else "usd"))
|
||
if price is not None and review_id is not None:
|
||
await asyncio.to_thread(db.add_cost, review_id, price)
|
||
if review_id is not None:
|
||
await asyncio.to_thread(db.resume_paused, review_id)
|
||
finally:
|
||
_release(username, review_id)
|
||
await queue.put(None)
|
||
|
||
|
||
async def completions(request: Request):
|
||
import device_auth
|
||
device = await asyncio.to_thread(device_auth.require_device, request)
|
||
username = device["username"]
|
||
user = await asyncio.to_thread(db.get_user_by_email, username)
|
||
if not user or user.get("blocked") or user.get("deleted_at") or user.get("read_only"):
|
||
raise HTTPException(403, "Учётная запись не может пользоваться программой")
|
||
review_header = (request.headers.get("X-Review-Id") or "").strip()
|
||
tab_header = (request.headers.get("X-Tab-Id") or "").strip()
|
||
if bool(review_header) == bool(tab_header):
|
||
raise HTTPException(400, "Нужен ровно один заголовок: X-Review-Id или X-Tab-Id")
|
||
review = None
|
||
review_id = None
|
||
if review_header:
|
||
try:
|
||
review_id = int(review_header)
|
||
except ValueError:
|
||
raise HTTPException(400, "X-Review-Id: ожидается номер")
|
||
data = await asyncio.to_thread(db.get_review, username, review_id)
|
||
if data is None or data["review"]["status"] in ("done", "stopped", "failed", "abandoned"):
|
||
raise HTTPException(404, "Проверка не найдена или закрыта")
|
||
review = data["review"]
|
||
tab_id = review["tab_id"]
|
||
else:
|
||
owner = await asyncio.to_thread(db.tab_owner, tab_header)
|
||
if owner and owner != username:
|
||
raise HTTPException(404, "Диалог не найден")
|
||
if owner is None:
|
||
# Незнакомый диалог — новый: сайт заводит диалог первым сообщением, и шлюз
|
||
# делает так же. Иначе первый вопрос программы на новой учётке — 404.
|
||
await asyncio.to_thread(db.ensure_session, username, tab_header)
|
||
tab_id = tab_header
|
||
body = {}
|
||
try:
|
||
body = await request.json()
|
||
except Exception: # noqa: BLE001
|
||
raise HTTPException(400, "Тело запроса не разобралось")
|
||
if body.get("max_tokens") is not None:
|
||
try:
|
||
if int(body["max_tokens"]) <= 0:
|
||
raise ValueError
|
||
except (TypeError, ValueError):
|
||
raise HTTPException(400, "max_tokens: ожидается положительное целое")
|
||
for m in (body.get("messages") or []):
|
||
if not isinstance(m, dict):
|
||
continue
|
||
role = ROLE_MAP.get(m.get("role"), m.get("role"))
|
||
if role == "tool" and not m.get("tool_call_id"):
|
||
raise HTTPException(400, "Сообщению tool нужен tool_call_id")
|
||
if role == "assistant":
|
||
for call in (m.get("tool_calls") or []):
|
||
if not isinstance(call, dict) or not call.get("id"):
|
||
raise HTTPException(400, "Вызову инструмента в assistant нужен id")
|
||
bad_roles = [str(m.get("role")) for m in (body.get("messages") or [])
|
||
if isinstance(m, dict) and m.get("role") not in ROLE_MAP]
|
||
if bad_roles:
|
||
# Неизвестную роль нельзя тихо превратить в user: меняется уровень доверия.
|
||
raise HTTPException(400, f"Неизвестная роль сообщения: {bad_roles[0]!r}")
|
||
# Пределы — ДО вызова провайдера и АТОМАРНО с бронью: проверка и запись брони идут
|
||
# под одним замком, иначе два одновременных вызова оба проходят одну и ту же проверку.
|
||
import quotas
|
||
|
||
def _admit() -> tuple[int, dict | None]:
|
||
"""0 — можно; иначе код отказа и тело. Вызывается под _lock."""
|
||
limits = quotas.limits_snapshot(username)
|
||
release_at = (limits.get("next_release") or {}).get("at")
|
||
retry = (max(1, int(release_at - time.time())) if release_at
|
||
else 3600) # окно суточное: через секунду предел не освободится
|
||
if not limits.get("unlimited"):
|
||
rub_left = (limits.get("rub") or {}).get("left")
|
||
if rub_left is not None and rub_left < RESERVE_RUB:
|
||
return 429, {"error": "limit", "axis": "rub", "retry_seconds": retry,
|
||
"message": f"Суточный предел исчерпан; повторите через {retry} с."}
|
||
req_left = (limits.get("requests") or {}).get("left")
|
||
if req_left is not None and req_left < 1:
|
||
return 429, {"error": "limit", "axis": "requests", "retry_seconds": retry,
|
||
"message": "Предел числа обращений исчерпан."}
|
||
tok_left = (limits.get("tokens") or {}).get("left")
|
||
if tok_left is not None and tok_left <= 0:
|
||
return 429, {"error": "limit", "axis": "tokens", "retry_seconds": retry,
|
||
"message": "Предел токенов исчерпан."}
|
||
if review is not None and review_id is not None:
|
||
budget = float(review.get("budget_rub") or 0)
|
||
price = float(review.get("price_rub") or 0)
|
||
inflight = _inflight_review.get(review_id, 0)
|
||
if budget > 0 and price + (inflight + 1) * RESERVE_RUB > budget:
|
||
return 402, {"error": "budget",
|
||
"message": "Потолок проверки исчерпан — проверка остановлена."}
|
||
_reserve(username, review_id)
|
||
return 0, None
|
||
|
||
with _lock:
|
||
code, refusal = _admit()
|
||
if code == 429:
|
||
if review_id is not None:
|
||
await asyncio.to_thread(db.pause_review, review_id)
|
||
return _fail(request, 429, "quota_exceeded", refusal)
|
||
if code == 402:
|
||
await asyncio.to_thread(db.finish_review, review_id, "stopped", None, "budget")
|
||
return _fail(request, 402, "budget_exceeded", refusal)
|
||
import agent_provider
|
||
chain = await asyncio.to_thread(agent_provider.provider_chain, username)
|
||
if not chain:
|
||
_release(username, review_id) # бронь уже взята в _admit — не держим её зря
|
||
return _fail(request, 503, "provider_failed", {
|
||
"error": "provider", "message": "Провайдер модели не настроен."})
|
||
profile = chain[0]
|
||
model = profile.model
|
||
started = time.time()
|
||
usage_path = "gateway:review" if review_id is not None else "gateway:tab"
|
||
usage_id = await asyncio.to_thread(db.create_llm_usage_stub, username, tab_id, usage_path,
|
||
RESERVE_RUB, profile.name, model)
|
||
queue: asyncio.Queue = asyncio.Queue()
|
||
task = asyncio.create_task(_pump(username, review_id, profile, body, usage_id, model,
|
||
started, queue))
|
||
# Ждём первое событие (или конец) в пределах общего времени вызова: до первого байта
|
||
# ещё можно ответить 504 и не начинать поток.
|
||
try:
|
||
first = await asyncio.wait_for(queue.get(), timeout=CALL_TIMEOUT_SEC)
|
||
except asyncio.TimeoutError:
|
||
task.cancel()
|
||
await asyncio.gather(task, return_exceptions=True)
|
||
return _fail(request, 504, "provider_timeout", {
|
||
"error": "timeout", "message": "Провайдер не ответил вовремя."})
|
||
|
||
first_done = {"value": first}
|
||
rid = getattr(request.state, "request_id", "")
|
||
|
||
async def stream():
|
||
ev = first_done["value"]
|
||
while ev is not None:
|
||
if "delta" in ev:
|
||
yield _openai_sse(ev["delta"])
|
||
elif "tool_call" in ev:
|
||
yield _openai_tool_sse(ev["tool_call"])
|
||
elif "finish" in ev:
|
||
yield _openai_finish_sse(ev["finish"])
|
||
elif "error" in ev:
|
||
yield ("data: " + json.dumps({"error": {"message": ev["error"],
|
||
"code": ev.get("code")
|
||
or "provider_failed",
|
||
"request_id": rid}},
|
||
ensure_ascii=False) + "\n\n")
|
||
ev = await queue.get()
|
||
yield "data: [DONE]\n\n"
|
||
return StreamingResponse(stream(), media_type="text/event-stream")
|