1"""OpenAI-compatible streaming client used for both lead and worker models."""
2
3from __future__ import annotations
4
5import asyncio
6import json
7import random
8from dataclasses import dataclass, field
9from typing import Any
10from collections.abc import Callable
11
12import httpx
13
14from .auth import Token
15from .config import Config
16from .utils import redact_secrets
17
18USER_AGENT = "airouter/0.1 (OpenCode Go compatible orchestrator)"
19
20
21@dataclass
22class Usage:
23 prompt_tokens: int = 0
24 completion_tokens: int = 0
25 total_tokens: int = 0
26 reasoning_tokens: int = 0
27 cache_read_tokens: int = 0
28 cost: float = 0.0
29 allowance: float = 0.0
30 billing_source: str = ""
31
32 def add(self, other: Usage) -> None:
33 self.prompt_tokens += other.prompt_tokens
34 self.completion_tokens += other.completion_tokens
35 self.total_tokens += other.total_tokens
36 self.reasoning_tokens += other.reasoning_tokens
37 self.cache_read_tokens += other.cache_read_tokens
38 self.cost += other.cost
39 self.allowance += other.allowance
40 if other.billing_source:
41 self.billing_source = other.billing_source
42
43 def to_dict(self) -> dict[str, Any]:
44 return {
45 "prompt_tokens": self.prompt_tokens,
46 "completion_tokens": self.completion_tokens,
47 "total_tokens": self.total_tokens,
48 "reasoning_tokens": self.reasoning_tokens,
49 "cache_read_tokens": self.cache_read_tokens,
50 "cost": self.cost,
51 "allowance": self.allowance,
52 "billing_source": self.billing_source,
53 }
54
55 @classmethod
56 def from_dict(cls, data: dict[str, Any] | None) -> Usage:
57 data = data or {}
58 return cls(
59 prompt_tokens=int(data.get("prompt_tokens", 0)),
60 completion_tokens=int(data.get("completion_tokens", 0)),
61 total_tokens=int(data.get("total_tokens", 0)),
62 reasoning_tokens=int(data.get("reasoning_tokens", 0)),
63 cache_read_tokens=int(data.get("cache_read_tokens", 0)),
64 cost=float(data.get("cost", 0)),
65 allowance=float(data.get("allowance", 0)),
66 billing_source=str(data.get("billing_source", "")),
67 )
68
69
70@dataclass
71class ToolCall:
72 id: str
73 name: str
74 arguments: str
75
76 def parsed_args(self) -> dict[str, Any]:
77 raw = self.arguments.strip() or "{}"
78 value = json.loads(raw)
79 if not isinstance(value, dict):
80 raise ValueError("tool arguments must be a JSON object")
81 return value
82
83
84@dataclass
85class AssistantTurn:
86 content: str = ""
87 reasoning: str = ""
88 tool_calls: list[ToolCall] = field(default_factory=list)
89 usage: Usage = field(default_factory=Usage)
90 finish_reason: str | None = None
91
92 def as_message(self) -> dict[str, Any]:
93 message: dict[str, Any] = {"role": "assistant", "content": self.content or ""}
94 if self.tool_calls:
95 message["tool_calls"] = [
96 {
97 "id": tc.id,
98 "type": "function",
99 "function": {"name": tc.name, "arguments": tc.arguments or "{}"},
100 }
101 for tc in self.tool_calls
102 ]
103 return message
104
105
106class ProviderError(RuntimeError):
107 def __init__(
108 self,
109 message: str,
110 *,
111 status: int | None = None,
112 hint: str = "",
113 retryable: bool = False,
114 ) -> None:
115 super().__init__(message)
116 self.status = status
117 self.hint = hint
118 self.retryable = retryable
119
120 def display(self) -> str:
121 text = redact_secrets(str(self))
122 if self.hint:
123 text += f"\n\n{self.hint}"
124 return text
125
126
127def _error_message(payload: Any) -> str:
128 if isinstance(payload, dict):
129 error = payload.get("error")
130 if isinstance(error, dict):
131 return str(error.get("message") or error.get("type") or error)
132 if error:
133 return str(error)
134 if payload.get("message"):
135 return str(payload["message"])
136 return json.dumps(payload, ensure_ascii=False)[:2000] if payload else "неизвестная ошибка"
137
138
139def _error_hint(status: int | None, base_url: str, model: str) -> str:
140 if status == 401:
141 return (
142 "Токен не принят. Проверьте, что вы вошли в OpenCode (`opencode auth login`) "
143 "или задайте OPENCODE_API_KEY. Для OpenCode Go нужен ключ Go или OAuth-токен консоли."
144 )
145 if status == 402:
146 return (
147 "Недостаточно средств. Убедитесь, что base_url указывает на Go-эндпоинт "
148 "(`.../inference/go/openai/v1`) и что подписка Go активна."
149 )
150 if status == 403:
151 return (
152 "Доступ запрещён. Бесплатные модели OpenCode доступны только внутри OpenCode; "
153 "используйте платную модель или Go-подписку."
154 )
155 if status == 404:
156 return f"Модель {model!r} не найдена по адресу {base_url}. Проверьте имя модели."
157 if status == 429:
158 return "Слишком много запросов или исчерпан лимит. Подождите и повторите."
159 return ""
160
161
162class OpenAIClient:
163 """Streaming Chat Completions client with token rotation and retries."""
164
165 def __init__(self, config: Config, tokens: list[Token]) -> None:
166 self.config = config
167 self.tokens = tokens
168 self._token_index = 0
169 self._client = httpx.AsyncClient(
170 timeout=httpx.Timeout(
171 connect=20.0,
172 read=config.provider.request_timeout,
173 write=60.0,
174 pool=20.0,
175 ),
176 limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
177 headers={"User-Agent": USER_AGENT},
178 )
179 self.requests_made = 0
180
181 @property
182 def base_url(self) -> str:
183 return self.config.provider.base_url
184
185 @property
186 def endpoint(self) -> str:
187 base = self.base_url.rstrip("/")
188 if base.endswith("/chat/completions"):
189 return base
190 return base + "/chat/completions"
191
192 def _requires_auth(self) -> bool:
193 return "opencode.ai" in self.base_url or bool(self.tokens)
194
195 def current_token(self) -> Token | None:
196 if not self.tokens:
197 return None
198 return self.tokens[self._token_index % len(self.tokens)]
199
200 async def aclose(self) -> None:
201 await self._client.aclose()
202
203 async def stream_chat(
204 self,
205 *,
206 model: str,
207 messages: list[dict[str, Any]],
208 tools: list[dict[str, Any]] | None = None,
209 session_id: str,
210 on_text: Callable[[str], None] | None = None,
211 on_reasoning: Callable[[str], None] | None = None,
212 temperature: float | None = 0.2,
213 max_tokens: int | None = None,
214 extra_headers: dict[str, str] | None = None,
215 ) -> AssistantTurn:
216 if not self.tokens and self._requires_auth():
217 raise ProviderError("Нет токена для API", hint="Запустите `airouter doctor`.")
218
219 payload: dict[str, Any] = {
220 "model": model,
221 "messages": messages,
222 "stream": True,
223 "stream_options": {"include_usage": True},
224 }
225 if tools:
226 payload["tools"] = tools
227 payload["tool_choice"] = "auto"
228 if temperature is not None:
229 payload["temperature"] = temperature
230 if max_tokens:
231 payload["max_tokens"] = max_tokens
232
233 attempts = max(1, self.config.provider.max_retries)
234 token_attempts = max(1, len(self.tokens))
235 token_tries = 0
236 last_error: ProviderError | None = None
237 emitted = False
238
239 def wrapped_text(delta: str) -> None:
240 nonlocal emitted
241 emitted = True
242 if on_text:
243 on_text(delta)
244
245 def wrapped_reasoning(delta: str) -> None:
246 if on_reasoning:
247 on_reasoning(delta)
248
249 for attempt in range(attempts):
250 token = self.current_token()
251 try:
252 turn = await self._request_once(
253 payload,
254 token=token,
255 session_id=session_id,
256 on_text=wrapped_text,
257 on_reasoning=wrapped_reasoning,
258 extra_headers=extra_headers,
259 )
260 return turn
261 except ProviderError as exc:
262 last_error = exc
263 if exc.status == 401 and token_tries + 1 < max(token_attempts, 1):
264 token_tries += 1
265 self._token_index = (self._token_index + 1) % max(1, len(self.tokens))
266 continue
267 if exc.retryable and not emitted and attempt + 1 < attempts:
268 delay = min(20.0, (2**attempt) + random.uniform(0, 1.0))
269 await asyncio.sleep(delay)
270 continue
271 raise
272 except httpx.RequestError as exc:
273 last_error = ProviderError(
274 f"Сетевая ошибка при обращении к API: {type(exc).__name__}: {exc}",
275 retryable=True,
276 )
277 if not emitted and attempt + 1 < attempts:
278 await asyncio.sleep(min(20.0, 2**attempt + random.uniform(0, 1.0)))
279 continue
280 raise last_error from exc
281
282 raise last_error or ProviderError("Не удалось выполнить запрос")
283
284 async def _request_once(
285 self,
286 payload: dict[str, Any],
287 *,
288 token: Token | None,
289 session_id: str,
290 on_text: Callable[[str], None] | None,
291 on_reasoning: Callable[[str], None] | None,
292 extra_headers: dict[str, str] | None,
293 ) -> AssistantTurn:
294 headers = {
295 "Content-Type": "application/json",
296 "Accept": "text/event-stream",
297 "x-opencode-session": session_id,
298 }
299 if token is not None:
300 headers["Authorization"] = f"Bearer {token.value}"
301 if extra_headers:
302 headers.update(extra_headers)
303
304 self.requests_made += 1
305 try:
306 async with self._client.stream(
307 "POST", self.endpoint, json=payload, headers=headers
308 ) as response:
309 if response.status_code >= 400:
310 body = await response.aread()
311 text = body.decode("utf-8", errors="replace")
312 try:
313 parsed = json.loads(text)
314 except json.JSONDecodeError:
315 parsed = text
316 raise ProviderError(
317 f"HTTP {response.status_code}: {_error_message(parsed)}",
318 status=response.status_code,
319 hint=_error_hint(
320 response.status_code, self.base_url, str(payload.get("model", ""))
321 ),
322 retryable=response.status_code in (408, 409, 429) or response.status_code >= 500,
323 )
324
325 content_type = response.headers.get("content-type", "")
326 if "application/json" in content_type and "event-stream" not in content_type:
327 data = await response.json()
328 return self._turn_from_json(data, on_text=on_text, on_reasoning=on_reasoning)
329
330 return await self._read_sse(
331 response, on_text=on_text, on_reasoning=on_reasoning
332 )
333 except httpx.HTTPStatusError as exc:
334 raise ProviderError(f"HTTP {exc.response.status_code}: {exc}") from exc
335
336 async def _read_sse(
337 self,
338 response: httpx.Response,
339 *,
340 on_text: Callable[[str], None] | None,
341 on_reasoning: Callable[[str], None] | None,
342 ) -> AssistantTurn:
343 turn = AssistantTurn()
344 tool_acc: dict[int, dict[str, str]] = {}
345 emitted = False
346
347 async for line in response.aiter_lines():
348 line = line.strip()
349 if not line or line.startswith(":"):
350 continue
351 data = line[5:].strip() if line.startswith("data:") else line
352 if data == "[DONE]":
353 break
354 if not data:
355 continue
356 try:
357 chunk = json.loads(data)
358 except json.JSONDecodeError:
359 continue
360 if not isinstance(chunk, dict):
361 continue
362 if chunk.get("error"):
363 raise ProviderError(
364 _error_message(chunk),
365 hint=_error_hint(None, self.base_url, ""),
366 retryable=False,
367 )
368
369 usage_raw = chunk.get("usage")
370 if usage_raw:
371 turn.usage = self._parse_usage(usage_raw)
372
373 choices = chunk.get("choices") or []
374 if not choices:
375 continue
376 choice = choices[0] or {}
377 if choice.get("finish_reason"):
378 turn.finish_reason = str(choice["finish_reason"])
379 delta = choice.get("delta") or choice.get("message") or {}
380 if not isinstance(delta, dict):
381 continue
382
383 text = delta.get("content")
384 if isinstance(text, str) and text:
385 turn.content += text
386 emitted = True
387 if on_text:
388 on_text(text)
389 reasoning = delta.get("reasoning_content") or delta.get("reasoning")
390 if isinstance(reasoning, str) and reasoning:
391 turn.reasoning += reasoning
392 if on_reasoning:
393 on_reasoning(reasoning)
394
395 for item in delta.get("tool_calls") or []:
396 if not isinstance(item, dict):
397 continue
398 index = int(item.get("index", 0) or 0)
399 slot = tool_acc.setdefault(
400 index, {"id": "", "name": "", "arguments": ""}
401 )
402 if item.get("id"):
403 slot["id"] = str(item["id"])
404 fn = item.get("function") or {}
405 if isinstance(fn, dict):
406 if fn.get("name"):
407 slot["name"] += str(fn["name"])
408 if fn.get("arguments"):
409 slot["arguments"] += str(fn["arguments"])
410
411 if not emitted and not tool_acc and turn.finish_reason is None:
412 # A 200 response that produced nothing is usually a proxy/API hiccup.
413 raise ProviderError("API вернул пустой поток без ответа", retryable=True)
414
415 for index in sorted(tool_acc):
416 slot = tool_acc[index]
417 if not slot["name"]:
418 continue
419 turn.tool_calls.append(
420 ToolCall(
421 id=slot["id"] or f"call_{index}",
422 name=slot["name"],
423 arguments=slot["arguments"] or "{}",
424 )
425 )
426 return turn
427
428 def _turn_from_json(
429 self,
430 data: dict[str, Any],
431 *,
432 on_text: Callable[[str], None] | None,
433 on_reasoning: Callable[[str], None] | None,
434 ) -> AssistantTurn:
435 if data.get("error"):
436 raise ProviderError(_error_message(data))
437 turn = AssistantTurn()
438 if data.get("usage"):
439 turn.usage = self._parse_usage(data["usage"])
440 choices = data.get("choices") or []
441 if not choices:
442 raise ProviderError("API вернул ответ без choices")
443 choice = choices[0] or {}
444 message = choice.get("message") or {}
445 turn.finish_reason = choice.get("finish_reason")
446 content = message.get("content")
447 if isinstance(content, str):
448 turn.content = content
449 if content and on_text:
450 on_text(content)
451 reasoning = message.get("reasoning_content") or message.get("reasoning")
452 if isinstance(reasoning, str):
453 turn.reasoning = reasoning
454 if reasoning and on_reasoning:
455 on_reasoning(reasoning)
456 for index, item in enumerate(message.get("tool_calls") or []):
457 fn = (item or {}).get("function") or {}
458 turn.tool_calls.append(
459 ToolCall(
460 id=str(item.get("id") or f"call_{index}"),
461 name=str(fn.get("name") or ""),
462 arguments=str(fn.get("arguments") or "{}"),
463 )
464 )
465 return turn
466
467 @staticmethod
468 def _parse_usage(raw: dict[str, Any]) -> Usage:
469 prompt = int(raw.get("prompt_tokens") or raw.get("input_tokens") or 0)
470 completion = int(raw.get("completion_tokens") or raw.get("output_tokens") or 0)
471 total = int(raw.get("total_tokens") or prompt + completion)
472 details = raw.get("completion_tokens_details") or {}
473 prompt_details = raw.get("prompt_tokens_details") or {}
474 opencode = raw.get("opencode") or {}
475 return Usage(
476 prompt_tokens=prompt,
477 completion_tokens=completion,
478 total_tokens=total,
479 reasoning_tokens=int(details.get("reasoning_tokens") or 0),
480 cache_read_tokens=int(prompt_details.get("cached_tokens") or 0),
481 cost=float(raw.get("cost") or 0),
482 allowance=float(opencode.get("allowance") or 0),
483 billing_source=str(opencode.get("billing_source") or ""),
484 )