"""Provider-independent chat interface with retries and structured output."""
from __future__ import annotations
import json
import logging
import re
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Literal
from ..config import LLMConfig
log = logging.getLogger(__name__)
[docs]
@dataclass
class ChatMessage:
role: Literal["user", "assistant"]
content: str
images: list[bytes] = field(default_factory=list) # JPEG bytes, user turns only
class LLMError(RuntimeError):
"""Raised when the provider cannot produce an answer after all retries."""
[docs]
class LLMProvider(ABC):
"""Subclasses implement ``_complete``; this class adds retries and back-off."""
def __init__(self, cfg: LLMConfig):
self.cfg = cfg
[docs]
def complete(
self,
system: str,
messages: list[ChatMessage],
schema: dict | None = None,
) -> str:
"""Return the model's text. With ``schema``, the text is a JSON object that the
provider was asked (and, where supported, constrained) to match."""
delay = 1.0
for attempt in range(self.cfg.retries + 1):
try:
return self._complete(system, messages, schema)
except Exception as exc: # SDK error types differ per provider
if attempt >= self.cfg.retries or not self._retryable(exc):
raise LLMError(f"{type(exc).__name__}: {exc}") from exc
log.warning(
"LLM call failed (%s); retry %d/%d in %.1fs",
exc,
attempt + 1,
self.cfg.retries,
delay,
)
time.sleep(delay)
delay *= 2
raise LLMError("unreachable")
@abstractmethod
def _complete(self, system: str, messages: list[ChatMessage], schema: dict | None) -> str: ...
@staticmethod
def _retryable(exc: Exception) -> bool:
status = getattr(exc, "status_code", None) or getattr(exc, "code", None)
if isinstance(status, int):
return status in (408, 409, 429) or status >= 500
name = type(exc).__name__
return any(k in name for k in ("Timeout", "Connection", "ServerError", "Unavailable"))
def extract_json(text: str) -> dict:
"""Parse the first JSON object in ``text`` (tolerates code fences and preambles)."""
text = text.strip()
fence = re.search(r"```(?:json)?\s*(.*?)```", text, re.DOTALL)
if fence:
text = fence.group(1).strip()
start = text.find("{")
if start < 0:
raise ValueError("no JSON object in the model output")
obj, _ = json.JSONDecoder().raw_decode(text[start:])
if not isinstance(obj, dict):
raise ValueError("model output is not a JSON object")
return obj