Files

657 lines
25 KiB
Python

"""OpenAI-compatible streaming client used for both lead and worker models."""
from __future__ import annotations
import asyncio
import json
import math
import random
from collections.abc import Callable
from dataclasses import dataclass, field
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from typing import Any
from urllib.parse import urlsplit
import httpx
from .auth import Token
from .config import Config
from .utils import redact_secrets
USER_AGENT = "airouter/0.1 (OpenCode Go compatible orchestrator)"
RETRYABLE_STATUS_CODES = {408, 409, 425, 429, 500, 502, 503, 504}
MAX_RETRY_DELAY = 60.0
@dataclass
class Usage:
prompt_tokens: int = 0
completion_tokens: int = 0
total_tokens: int = 0
reasoning_tokens: int = 0
cache_read_tokens: int = 0
cost: float = 0.0
allowance: float = 0.0
billing_source: str = ""
def add(self, other: Usage) -> None:
self.prompt_tokens += other.prompt_tokens
self.completion_tokens += other.completion_tokens
self.total_tokens += other.total_tokens
self.reasoning_tokens += other.reasoning_tokens
self.cache_read_tokens += other.cache_read_tokens
self.cost += other.cost
self.allowance += other.allowance
if other.billing_source:
self.billing_source = other.billing_source
def to_dict(self) -> dict[str, Any]:
return {
"prompt_tokens": self.prompt_tokens,
"completion_tokens": self.completion_tokens,
"total_tokens": self.total_tokens,
"reasoning_tokens": self.reasoning_tokens,
"cache_read_tokens": self.cache_read_tokens,
"cost": self.cost,
"allowance": self.allowance,
"billing_source": self.billing_source,
}
@classmethod
def from_dict(cls, data: dict[str, Any] | None) -> Usage:
data = data or {}
return cls(
prompt_tokens=int(data.get("prompt_tokens", 0)),
completion_tokens=int(data.get("completion_tokens", 0)),
total_tokens=int(data.get("total_tokens", 0)),
reasoning_tokens=int(data.get("reasoning_tokens", 0)),
cache_read_tokens=int(data.get("cache_read_tokens", 0)),
cost=float(data.get("cost", 0)),
allowance=float(data.get("allowance", 0)),
billing_source=str(data.get("billing_source", "")),
)
@dataclass
class ToolCall:
id: str
name: str
arguments: str
def parsed_args(self) -> dict[str, Any]:
raw = self.arguments.strip() or "{}"
value = json.loads(raw)
if not isinstance(value, dict):
raise ValueError("tool arguments must be a JSON object")
return value
@dataclass
class AssistantTurn:
content: str = ""
reasoning: str = ""
tool_calls: list[ToolCall] = field(default_factory=list)
usage: Usage = field(default_factory=Usage)
finish_reason: str | None = None
def as_message(self) -> dict[str, Any]:
message: dict[str, Any] = {"role": "assistant", "content": self.content or ""}
if self.tool_calls:
message["tool_calls"] = [
{
"id": tc.id,
"type": "function",
"function": {"name": tc.name, "arguments": tc.arguments or "{}"},
}
for tc in self.tool_calls
]
return message
class ProviderError(RuntimeError):
def __init__(
self,
message: str,
*,
status: int | None = None,
hint: str = "",
retryable: bool = False,
retry_after: float | None = None,
attempts: int | None = None,
) -> None:
super().__init__(message)
self.status = status
self.hint = hint
self.retryable = retryable
self.retry_after = retry_after
self.attempts = attempts
def display(self) -> str:
text = redact_secrets(str(self))
if self.hint:
text += f"\n\n{self.hint}"
if self.attempts:
text += f"\n\nВыполнено попыток: {self.attempts}."
return text
def _error_message(payload: Any) -> str:
if isinstance(payload, dict):
error = payload.get("error")
if isinstance(error, dict):
return str(error.get("message") or error.get("type") or error)
if error:
return str(error)
if payload.get("message"):
return str(payload["message"])
return json.dumps(payload, ensure_ascii=False)[:2000] if payload else "неизвестная ошибка"
def _hostname(base_url: str) -> str:
try:
return (urlsplit(base_url).hostname or "").lower()
except ValueError:
return ""
def _is_opencode_url(base_url: str) -> bool:
host = _hostname(base_url)
return host == "opencode.ai" or host.endswith(".opencode.ai")
def _is_local_url(base_url: str) -> bool:
host = _hostname(base_url)
return host in {"localhost", "127.0.0.1", "::1"} or host.endswith(".localhost")
def _parse_retry_after(value: str | None) -> float | None:
if not value:
return None
try:
seconds = float(value.strip())
if math.isfinite(seconds):
return max(0.0, seconds)
except (TypeError, ValueError):
pass
try:
parsed = parsedate_to_datetime(value)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return max(0.0, (parsed - datetime.now(timezone.utc)).total_seconds())
except (TypeError, ValueError, OverflowError):
return None
def _error_hint(
status: int | None,
base_url: str,
model: str,
profile_id: str | None = None,
) -> str:
is_opencode = _is_opencode_url(base_url) or profile_id == "opencode"
is_local = _is_local_url(base_url)
provider_label = profile_id or "провайдера"
if status == 401:
if is_opencode:
return (
"Токен не принят. Проверьте, что вы вошли в OpenCode (`opencode auth login`) "
"или задайте OPENCODE_API_KEY. Для OpenCode Go нужен ключ Go или OAuth-токен консоли."
)
return (
f"Токен не принят провайдером {provider_label!r}. Проверьте token/token_env "
"или соответствующую переменную окружения этого провайдера."
)
if status == 402:
if is_opencode:
return (
"Недостаточно средств. Убедитесь, что base_url указывает на Go-эндпоинт "
"(`.../inference/go/openai/v1`) и что подписка Go активна."
)
return "Недостаточно средств на счёте провайдера. Проверьте тариф и баланс API."
if status == 403:
if is_opencode:
return (
"Доступ запрещён. Бесплатные модели OpenCode доступны только внутри OpenCode; "
"используйте платную модель или Go-подписку."
)
return "Доступ запрещён. Проверьте права токена, доступ к модели и ограничения провайдера."
if status == 404:
hint = f"Модель {model!r} не найдена по адресу {base_url}. Проверьте имя модели."
if is_local:
hint += " Возможно, модель ещё не загружена на локальном сервере."
return hint
if status == 429:
return "Слишком много запросов или исчерпан лимит. Подождите и повторите."
if is_local:
if status in {408, 409, 425}:
return "Локальный сервер перегружен или завершил запрос. Проверьте его журнал и повторите."
return (
"Локальный сервер отклонил запрос. Проверьте его журнал, base_url, "
"имя модели и поддерживаемые параметры."
)
if status == 400:
return "Запрос отклонён провайдером. Проверьте имя модели, сообщения и параметры."
if status is not None and status >= 500:
return "Временная ошибка сервера провайдера. Повторите запрос позже."
if status is not None:
return f"Провайдер {provider_label!r} вернул HTTP {status}. Проверьте его документацию и журнал."
return ""
def _network_error_hint(base_url: str, profile_id: str | None = None) -> str:
if _is_local_url(base_url):
return (
f"Не удалось подключиться к локальному серверу {base_url}. Проверьте, что он "
"запущен, base_url корректен и порт доступен."
)
if _is_opencode_url(base_url) or profile_id == "opencode":
return "Проверьте подключение к OpenCode и доступность Go-эндпоинта."
return "Проверьте подключение к интернету, base_url провайдера и настройки прокси."
class OpenAIClient:
"""Streaming Chat Completions client with token rotation and retries."""
def __init__(
self,
config: Config,
tokens: list[Token],
profile_id: str | None = None,
*,
on_retry: Callable[[int, int, float, str], None] | None = None,
) -> None:
self.config = config
self.tokens = tokens
self.profile_id = profile_id
self.on_retry = on_retry
self._token_index = 0
self._client = httpx.AsyncClient(
timeout=httpx.Timeout(
connect=20.0,
read=config.provider.request_timeout,
write=60.0,
pool=20.0,
),
limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
headers={"User-Agent": USER_AGENT},
)
self.requests_made = 0
@property
def base_url(self) -> str:
return self.config.provider.base_url
@property
def endpoint(self) -> str:
base = self.base_url.rstrip("/")
if base.endswith("/chat/completions"):
return base
return base + "/chat/completions"
def _requires_auth(self) -> bool:
return "opencode.ai" in self.base_url or bool(self.tokens)
def current_token(self) -> Token | None:
if not self.tokens:
return None
return self.tokens[self._token_index % len(self.tokens)]
async def aclose(self) -> None:
await self._client.aclose()
async def stream_chat(
self,
*,
model: str,
messages: list[dict[str, Any]],
tools: list[dict[str, Any]] | None = None,
session_id: str,
on_text: Callable[[str], None] | None = None,
on_reasoning: Callable[[str], None] | None = None,
temperature: float | None = 0.2,
max_tokens: int | None = None,
extra_headers: dict[str, str] | None = None,
on_retry: Callable[[int, int, float, str], None] | None = None,
) -> AssistantTurn:
if not self.tokens and self._requires_auth():
raise ProviderError("Нет токена для API", hint="Запустите `airouter doctor`.")
payload: dict[str, Any] = {
"model": model,
"messages": messages,
"stream": True,
"stream_options": {"include_usage": True},
}
if tools:
payload["tools"] = tools
payload["tool_choice"] = "auto"
if temperature is not None:
payload["temperature"] = temperature
if max_tokens:
payload["max_tokens"] = max_tokens
attempts = max(1, self.config.provider.max_retries)
token_attempts = max(1, len(self.tokens))
token_tries = 0
last_error: ProviderError | None = None
emitted = False
def mark_emitted() -> None:
nonlocal emitted
emitted = True
def wrapped_text(delta: str) -> None:
mark_emitted()
if on_text:
on_text(delta)
def wrapped_reasoning(delta: str) -> None:
mark_emitted()
if on_reasoning:
on_reasoning(delta)
async def retry_wait(
attempt: int, error: ProviderError, reason: str
) -> None:
if error.retry_after is not None:
delay = min(MAX_RETRY_DELAY, max(0.0, error.retry_after))
else:
delay = min(
MAX_RETRY_DELAY,
(2 ** min(attempt, 6)) + random.uniform(0.0, 1.0),
)
retry_callback = on_retry if on_retry is not None else getattr(self, "on_retry", None)
if retry_callback:
retry_callback(attempt + 1, attempts, delay, reason)
await asyncio.sleep(delay)
for attempt in range(attempts):
token = self.current_token()
try:
turn = await self._request_once(
payload,
token=token,
session_id=session_id,
on_text=wrapped_text,
on_reasoning=wrapped_reasoning,
extra_headers=extra_headers,
on_emitted=mark_emitted,
)
return turn
except ProviderError as exc:
exc.attempts = attempt + 1
last_error = exc
if (
exc.status == 401
and not emitted
and token_tries + 1 < max(token_attempts, 1)
):
token_tries += 1
self._token_index = (self._token_index + 1) % max(1, len(self.tokens))
continue
if exc.retryable and not emitted and attempt + 1 < attempts:
await retry_wait(attempt, exc, f"HTTP {exc.status}")
continue
raise
except (httpx.RequestError, TimeoutError, ConnectionError) as exc:
last_error = ProviderError(
f"Сетевая ошибка при обращении к API: {type(exc).__name__}: {exc}",
hint=_network_error_hint(
self.base_url, getattr(self, "profile_id", None)
),
retryable=True,
attempts=attempt + 1,
)
if not emitted and attempt + 1 < attempts:
await retry_wait(attempt, last_error, type(exc).__name__)
continue
raise last_error from exc
raise last_error or ProviderError("Не удалось выполнить запрос")
async def _request_once(
self,
payload: dict[str, Any],
*,
token: Token | None,
session_id: str,
on_text: Callable[[str], None] | None,
on_reasoning: Callable[[str], None] | None,
extra_headers: dict[str, str] | None,
on_emitted: Callable[[], None] | None = None,
) -> AssistantTurn:
headers = {
"Content-Type": "application/json",
"Accept": "text/event-stream",
"x-opencode-session": session_id,
}
if token is not None:
headers["Authorization"] = f"Bearer {token.value}"
if extra_headers:
headers.update(extra_headers)
self.requests_made += 1
try:
async with self._client.stream(
"POST", self.endpoint, json=payload, headers=headers
) as response:
if response.status_code >= 400:
body = await response.aread()
text = body.decode("utf-8", errors="replace")
try:
parsed = json.loads(text)
except json.JSONDecodeError:
parsed = text
raise ProviderError(
f"HTTP {response.status_code}: {_error_message(parsed)}",
status=response.status_code,
hint=_error_hint(
response.status_code,
self.base_url,
str(payload.get("model", "")),
getattr(self, "profile_id", None),
),
retryable=response.status_code in RETRYABLE_STATUS_CODES,
retry_after=_parse_retry_after(response.headers.get("Retry-After")),
)
content_type = response.headers.get("content-type", "")
if "application/json" in content_type and "event-stream" not in content_type:
data = await response.json()
return self._turn_from_json(
data,
on_text=on_text,
on_reasoning=on_reasoning,
on_emitted=on_emitted,
)
return await self._read_sse(
response,
on_text=on_text,
on_reasoning=on_reasoning,
on_emitted=on_emitted,
)
except httpx.HTTPStatusError as exc:
status = exc.response.status_code
raise ProviderError(
f"HTTP {status}: {exc}",
status=status,
hint=_error_hint(
status,
self.base_url,
str(payload.get("model", "")),
getattr(self, "profile_id", None),
),
retryable=status in RETRYABLE_STATUS_CODES,
retry_after=_parse_retry_after(exc.response.headers.get("Retry-After")),
) from exc
async def _read_sse(
self,
response: httpx.Response,
*,
on_text: Callable[[str], None] | None,
on_reasoning: Callable[[str], None] | None,
on_emitted: Callable[[], None] | None = None,
) -> AssistantTurn:
turn = AssistantTurn()
tool_acc: dict[int, dict[str, str]] = {}
emitted = False
async for line in response.aiter_lines():
line = line.strip()
if not line or line.startswith(":"):
continue
data = line[5:].strip() if line.startswith("data:") else line
if data == "[DONE]":
break
if not data:
continue
try:
chunk = json.loads(data)
except json.JSONDecodeError:
continue
if not isinstance(chunk, dict):
continue
if chunk.get("error"):
raise ProviderError(
_error_message(chunk),
hint=_error_hint(None, self.base_url, ""),
retryable=False,
)
usage_raw = chunk.get("usage")
if usage_raw:
turn.usage = self._parse_usage(usage_raw)
choices = chunk.get("choices") or []
if not choices:
continue
choice = choices[0] or {}
if choice.get("finish_reason"):
turn.finish_reason = str(choice["finish_reason"])
delta = choice.get("delta") or choice.get("message") or {}
if not isinstance(delta, dict):
continue
text = delta.get("content")
if isinstance(text, str) and text:
turn.content += text
emitted = True
if on_emitted:
on_emitted()
if on_text:
on_text(text)
reasoning = delta.get("reasoning_content") or delta.get("reasoning")
if isinstance(reasoning, str) and reasoning:
turn.reasoning += reasoning
emitted = True
if on_emitted:
on_emitted()
if on_reasoning:
on_reasoning(reasoning)
for item in delta.get("tool_calls") or []:
if not isinstance(item, dict):
continue
index = int(item.get("index", 0) or 0)
emitted = True
if on_emitted:
on_emitted()
slot = tool_acc.setdefault(
index, {"id": "", "name": "", "arguments": ""}
)
if item.get("id"):
slot["id"] = str(item["id"])
fn = item.get("function") or {}
if isinstance(fn, dict):
if fn.get("name"):
slot["name"] += str(fn["name"])
if fn.get("arguments"):
slot["arguments"] += str(fn["arguments"])
if not emitted and not tool_acc and turn.finish_reason is None:
# A 200 response that produced nothing is usually a proxy/API hiccup.
raise ProviderError("API вернул пустой поток без ответа", retryable=True)
for index in sorted(tool_acc):
slot = tool_acc[index]
if not slot["name"]:
continue
turn.tool_calls.append(
ToolCall(
id=slot["id"] or f"call_{index}",
name=slot["name"],
arguments=slot["arguments"] or "{}",
)
)
return turn
def _turn_from_json(
self,
data: dict[str, Any],
*,
on_text: Callable[[str], None] | None,
on_reasoning: Callable[[str], None] | None,
on_emitted: Callable[[], None] | None = None,
) -> AssistantTurn:
if data.get("error"):
raise ProviderError(_error_message(data))
turn = AssistantTurn()
if data.get("usage"):
turn.usage = self._parse_usage(data["usage"])
choices = data.get("choices") or []
if not choices:
raise ProviderError("API вернул ответ без choices")
choice = choices[0] or {}
message = choice.get("message") or {}
turn.finish_reason = choice.get("finish_reason")
content = message.get("content")
if isinstance(content, str):
turn.content = content
if content:
if on_emitted:
on_emitted()
if on_text:
on_text(content)
reasoning = message.get("reasoning_content") or message.get("reasoning")
if isinstance(reasoning, str):
turn.reasoning = reasoning
if reasoning:
if on_emitted:
on_emitted()
if on_reasoning:
on_reasoning(reasoning)
for index, item in enumerate(message.get("tool_calls") or []):
if on_emitted:
on_emitted()
fn = (item or {}).get("function") or {}
turn.tool_calls.append(
ToolCall(
id=str(item.get("id") or f"call_{index}"),
name=str(fn.get("name") or ""),
arguments=str(fn.get("arguments") or "{}"),
)
)
return turn
@staticmethod
def _parse_usage(raw: dict[str, Any]) -> Usage:
prompt = int(raw.get("prompt_tokens") or raw.get("input_tokens") or 0)
completion = int(raw.get("completion_tokens") or raw.get("output_tokens") or 0)
total = int(raw.get("total_tokens") or prompt + completion)
details = raw.get("completion_tokens_details") or {}
prompt_details = raw.get("prompt_tokens_details") or {}
opencode = raw.get("opencode") or {}
return Usage(
prompt_tokens=prompt,
completion_tokens=completion,
total_tokens=total,
reasoning_tokens=int(details.get("reasoning_tokens") or 0),
cache_read_tokens=int(prompt_details.get("cached_tokens") or 0),
cost=float(raw.get("cost") or 0),
allowance=float(opencode.get("allowance") or 0),
billing_source=str(opencode.get("billing_source") or ""),
)