Skip to content

The platform for continuously improving AI agents.

35.3 KB
Raw Blame
import asyncio
import json
import logging
import os
import threading
import time
from collections.abc import Callable
from contextlib import suppress
from dataclasses import dataclass, field
from functools import lru_cache
from types import SimpleNamespace
from typing import Any, Literal
from urllib.parse import parse_qsl, urlsplit, urlunsplit

import json_repair
import openai
from celery.exceptions import SoftTimeLimitExceeded
from openai import AsyncOpenAI, OpenAI
from openai.lib._pydantic import to_strict_json_schema
from pydantic import BaseModel
from tenacity import (
    AsyncRetrying,
    RetryCallState,
    before_sleep_log,
    stop_after_attempt,
    stop_after_delay,
    wait_exponential_jitter,
)

from modal_shared import container_meter
from modal_shared.context_budget import INCOMPLETE_FINISH_REASONS
from modal_shared.modelfam import serve_image_key
from modal_shared.shared import routing_headers as _modal_routing_headers
from overbae.core.model_registry import (
    OPENROUTER_BASE_URL,
    PROVIDERS,
    Provider,
    TaskType,
    is_decision_model,
    normalize_model_name,
    openrouter_slug,
    reasoning_of,
    resolve_model,
)
from overbae.models import DeployedModel
from overbae.services import model_meter

logger = logging.getLogger(__name__)

# Seconds per completion. The SDK default of 600s lets one hung socket read pin
# a `--pool=threads` worker thread long enough to starve the queue, so this stays
# well above a healthy completion but far below the default. Total retry time is
# bounded by a cancellable elapsed deadline, including retries and heartbeats.
_REQUEST_TIMEOUT = float(os.environ.get("LLM_REQUEST_TIMEOUT", "120"))

# Reasoning models spend hidden reasoning tokens out of the same completion
# budget as the visible answer, so a bare ``max_tokens`` can be consumed entirely
# by reasoning and return ``finish_reason="length"`` with empty content. This
# headroom is added only for reasoning models, leaving other budgets untouched.
_REASONING_TOKEN_HEADROOM = int(os.environ.get("LLM_REASONING_TOKEN_HEADROOM", "12000"))

_RETRYABLE_OPENAI_ERRORS = (
    openai.RateLimitError,
    openai.InternalServerError,
    openai.APIConnectionError,
)

_NON_RETRYABLE_MESSAGE_MARKERS = (
    "missing credentials",
    "authentication_error",
)


@dataclass(frozen=True)
class ModelSpec:
    """A model outside the hardcoded :data:`SUPPORTED_LLM_MODELS` catalog —
    fine-tunes and custom OpenAI-compatible endpoints — built from a ``ModelRef``.
    """

    provider: str  # openai | anthropic | gemini | custom
    model_id: str
    base_url: str = ""
    # Env var name; secrets are never persisted.
    api_key_env: str = ""
    params: dict[str, Any] = field(default_factory=dict)


class IncompleteCompletionError(RuntimeError):
    def __init__(self, content: str, stats: dict):
        super().__init__("The model reached its output token limit before completing the response.")
        self.content = content
        self.stats = stats


# ``_do_openai_completion`` owns chat retries. The SDK's own loop would retry a
# credential error before our fail-fast check and swallow a worker's soft time limit.
_SDK_RETRIES = 0


def _provider_client(provider: str | Provider) -> AsyncOpenAI:
    provider = PROVIDERS[provider] if isinstance(provider, str) else provider
    api_key = provider.key()
    if not api_key:
        raise RuntimeError(f"{provider.key_env} is required for LLM completions")
    return AsyncOpenAI(
        api_key=api_key,
        base_url=provider.base_url,
        default_headers=provider.headers or None,
        timeout=_REQUEST_TIMEOUT,
        max_retries=_SDK_RETRIES,
    )


def openrouter_client() -> AsyncOpenAI:
    return _provider_client("openrouter")


@lru_cache(maxsize=1)
def _openai_client() -> OpenAI:
    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        raise RuntimeError("OPENAI_API_KEY is required")
    return OpenAI(api_key=api_key, timeout=_REQUEST_TIMEOUT)


def _openai_compatible_client(
    base_url: str,
    api_key: str,
    query_items: tuple[tuple[str, str], ...] = (),
    header_items: tuple[tuple[str, str], ...] = (),
) -> AsyncOpenAI:
    # ``query_items`` are routing params that must ride on every request. Passing
    # them via ``default_query`` keeps them after the appended
    # ``/chat/completions`` path; baked into ``base_url`` they get corrupted.
    return AsyncOpenAI(
        api_key=api_key,
        base_url=base_url,
        timeout=_REQUEST_TIMEOUT,
        max_retries=_SDK_RETRIES,
        default_query=dict(query_items) or None,
        default_headers=dict(header_items) or None,
    )


def _inference_routing_header_items(model_id: str) -> tuple[tuple[str, str], ...]:
    """Postgres routing for Modal gateway calls. Empty if the row is missing."""
    # Deployment imports training monitoring while model registration imports this module.
    from overbae.services.deployment import saved_base_identity, serving_gpu

    dep = (
        DeployedModel.objects.filter(model_id=model_id)
        .exclude(weights_path="")
        .exclude(gpu_type="")
        .first()
    )
    if dep is None:
        return ()
    return tuple(
        sorted(
            _modal_routing_headers(
                gpu_type=serving_gpu(dep),
                weights_path=dep.weights_path,
                max_model_len=dep.max_model_len,
                serve_image=serve_image_key(dep.base_model_id, dep.model_id),
                adapter_path=dep.adapter_path or "",
                lora_rank=dep.lora_rank or 0,
                base_identity=saved_base_identity(dep),
            ).items()
        )
    )


def _split_base_url(url: str) -> tuple[str, tuple[tuple[str, str], ...]]:
    """Return ``(base_without_query, query_items)`` — see _openai_compatible_client."""
    parts = urlsplit(url)
    base = urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
    return base, tuple(parse_qsl(parts.query))


def _model_spec_client_and_name(spec: ModelSpec) -> tuple[AsyncOpenAI, str, str]:
    provider = (spec.provider or "").lower()
    if provider == "custom":
        if not spec.base_url:
            raise RuntimeError(f"Custom model '{spec.model_id}' requires base_url")
        if not spec.api_key_env:
            raise RuntimeError(f"Custom model '{spec.model_id}' requires api_key_env")
        api_key = os.environ.get(spec.api_key_env)
        if not api_key:
            raise RuntimeError(f"{spec.api_key_env} is required for custom model '{spec.model_id}'")
        base, query_items = _split_base_url(spec.base_url)
        header_items = ()
        if spec.api_key_env == "INFERENCE_API_KEY":
            header_items = _inference_routing_header_items(spec.model_id)
            # The serving container charges this call's seconds to the caller's cause.
            found = model_meter.current()
            if found is not None:
                header_items = (*header_items, (container_meter.REF_HEADER, found.ref))
        return (
            _openai_compatible_client(base, api_key, query_items, header_items),
            spec.model_id,
            provider,
        )

    slug = openrouter_slug(spec.model_id)
    return openrouter_client(), slug, "openrouter"


def effective_max_tokens(model_name: str, max_tokens: int = 5000) -> int:
    """``max_tokens`` stays the caller's intended visible-output size; reasoning
    models get extra room so hidden reasoning cannot starve the answer.
    """
    if reasoning_of(model_name).adaptive is not None:
        return max_tokens + _REASONING_TOKEN_HEADROOM
    return max_tokens


def _get_default_model() -> str:
    return resolve_model(TaskType.DEFAULT)


def _should_retry_llm_call(retry_state: RetryCallState) -> bool:
    exc = retry_state.outcome.exception()
    if exc is None:
        return False
    return _retryable_llm_error(exc)


def _retryable_llm_error(exc: BaseException) -> bool:
    if isinstance(exc, _RETRYABLE_OPENAI_ERRORS):
        pass
    elif isinstance(exc, openai.APIStatusError):
        if exc.status_code < 500:
            return False
    else:
        return False
    message = str(exc).lower()
    return not any(marker in message for marker in _NON_RETRYABLE_MESSAGE_MARKERS)


def completion_failure(exc: Exception) -> dict:
    cause = exc
    chain = []
    while cause is not None and all(cause is not item for item in chain):
        chain.append(cause)
        cause = cause.__cause__
    provider = next((item for item in chain if isinstance(item, openai.APIError)), exc)
    # Provider bodies can echo prompts or credentials; retain only bounded metadata.
    return {
        "error": type(exc).__name__,
        "cause": type(chain[-1]).__name__,
        "http_status": provider.status_code
        if isinstance(provider, openai.APIStatusError)
        else None,
        "retryable": _retryable_llm_error(provider)
        if isinstance(provider, openai.APIError)
        else any(
            isinstance(item, (IncompleteCompletionError, TimeoutError, SoftTimeLimitExceeded))
            for item in chain
        ),
    }


# A request path holds a browser connection open, so it must give up long before
# a Celery task does. Callers pass the deadline that suits them.
RETRY_DEADLINE_INTERACTIVE = float(os.environ.get("LLM_RETRY_DEADLINE_INTERACTIVE", "45"))
RETRY_DEADLINE_BACKGROUND = float(os.environ.get("LLM_RETRY_DEADLINE_BACKGROUND", "300"))


def _retry_after_seconds(exc: BaseException) -> float | None:
    """A 429 carries the wait the provider wants; blind backoff ignores it."""
    response = getattr(exc, "response", None)
    headers = getattr(response, "headers", None)
    if not headers:
        return None
    raw = headers.get("retry-after") or headers.get("Retry-After")
    if raw is None:
        return None
    try:
        return max(0.0, float(raw))
    except (TypeError, ValueError):
        # The header also permits an HTTP date; backing off blind is fine there.
        return None


class _WaitHonouringRetryAfter:
    def __init__(self, fallback):
        self._fallback = fallback

    def __call__(self, retry_state: RetryCallState) -> float:
        exc = retry_state.outcome.exception() if retry_state.outcome else None
        if exc is not None:
            after = _retry_after_seconds(exc)
            if after is not None:
                return min(after, 60.0)
        return self._fallback(retry_state)


_LLM_WAIT = _WaitHonouringRetryAfter(wait_exponential_jitter(initial=1, max=60, jitter=5))


class CompletionDeadlineExceededError(TimeoutError):
    """The total completion budget expired, even if the server kept sending bytes."""


def _is_openrouter(client: AsyncOpenAI | OpenAI) -> bool:
    return urlsplit(str(client.base_url)).hostname == urlsplit(OPENROUTER_BASE_URL).hostname


def _settle(response: Any, fallback_model: str) -> None:
    """Charge an answered OpenRouter request to the caller's billing cause."""
    usage = getattr(response, "usage", None)
    model_meter.settle(
        getattr(response, "id", None),
        _usage_value(usage, "cost", None),
        model=getattr(response, "model", None) or fallback_model,
        prompt_tokens=_usage_value(usage, "prompt_tokens", None),
        completion_tokens=_usage_value(usage, "completion_tokens", None),
    )


async def _create_completion(
    client: AsyncOpenAI,
    completion_kwargs: dict,
    request_kwargs: dict,
    retry_deadline: float = RETRY_DEADLINE_BACKGROUND,
    max_attempts: int | None = None,
    answered: list | None = None,
):
    async def _once():
        started = time.monotonic()
        try:
            response = await client.chat.completions.create(**completion_kwargs, **request_kwargs)
        except openai.APIConnectionError as exc:
            if isinstance(exc.__cause__, SoftTimeLimitExceeded):
                raise exc.__cause__ from None
            raise
        if answered is not None:
            answered.append(response)
        response_ms = (time.monotonic() - started) * 1000
        with suppress(AttributeError, TypeError):
            object.__setattr__(response, "_response_ms", response_ms)
        return response

    stop = stop_after_delay(retry_deadline)
    if max_attempts:
        stop |= stop_after_attempt(max_attempts)
    return await AsyncRetrying(
        retry=_should_retry_llm_call,
        wait=_LLM_WAIT,
        stop=stop,
        reraise=True,
        before_sleep=before_sleep_log(logger, logging.WARNING),
    )(_once)


def _do_openai_completion(
    client: AsyncOpenAI,
    completion_kwargs: dict,
    request_kwargs: dict,
    retry_deadline: float = RETRY_DEADLINE_BACKGROUND,
    max_attempts: int | None = None,
):
    # Each chat owns its client and loop. Cached asynchronous clients cannot be
    # reused across worker threads or across the loops of successive calls.
    budget = retry_deadline if retry_deadline > 0 else _REQUEST_TIMEOUT
    # Every answer the provider sent is billed, also one a later step rejects. A request
    # that timed out after it was sent has no generation id to charge: that cost is ours.
    answered: list = []

    async def complete():
        try:
            async with client, asyncio.timeout(budget):
                return await _create_completion(
                    client,
                    completion_kwargs,
                    request_kwargs,
                    retry_deadline,
                    max_attempts,
                    answered,
                )
        except TimeoutError as exc:
            raise CompletionDeadlineExceededError(
                f"Completion deadline exceeded after {budget:g}s"
            ) from exc

    try:
        return asyncio.run(complete())
    finally:
        if _is_openrouter(client):
            for response in answered:
                _settle(response, str(completion_kwargs.get("model", "")))


class EmbeddingUnavailableError(RuntimeError):
    """Raised when embeddings cannot run: they need a direct OpenAI key
    (OpenRouter does not proxy the embeddings API)."""


_EMBEDDING_MODEL = "text-embedding-3-small"


# Well under the 2048-input / payload ceilings; keeps each request small and retryable.
def _require_openai_key() -> None:
    if not os.environ.get("OPENAI_API_KEY"):
        raise EmbeddingUnavailableError(
            "Embeddings require OPENAI_API_KEY (text-embedding-3-small); "
            "OpenRouter does not proxy the embeddings API."
        )


def _vector(item: Any) -> list[float]:
    embedding = item["embedding"] if isinstance(item, dict) else item.embedding
    if embedding is None:
        raise ValueError("No embedding received")
    return embedding


def get_embedding(input_text: str) -> list[float]:
    _require_openai_key()
    response = _openai_client().embeddings.create(model=_EMBEDDING_MODEL, input=[input_text])
    return _vector(response.data[0])


def _extra(obj: Any) -> dict[str, Any]:
    value = getattr(obj, "model_extra", None)
    return value if isinstance(value, dict) else {}


def _usage_value(usage: Any, key: str, default: Any = 0) -> Any:
    extras = _extra(usage)
    if key in extras:
        return extras[key]
    value = getattr(usage, key, None)
    if value is not None:
        return value
    return default


def _cached_tokens(usage: Any) -> int:
    """Accounting metadata never fails a completion — an odd shape reads as zero."""
    details = getattr(usage, "prompt_tokens_details", None) or _extra(usage).get(
        "prompt_tokens_details"
    )
    raw = (
        details.get("cached_tokens")
        if isinstance(details, dict)
        else getattr(details, "cached_tokens", None)
    )
    try:
        return int(raw or 0)
    except (TypeError, ValueError):
        return 0


def _extract_llm_response(response) -> tuple[str, dict]:
    message = response.choices[0].message
    content = message.content
    tool_calls = getattr(message, "tool_calls", None)
    if tool_calls:
        content = json.dumps(
            {"content": content, "tool_calls": [tc.model_dump() for tc in tool_calls]}
        )
    elif content is None:
        if getattr(response.choices[0], "finish_reason", None) in INCOMPLETE_FINISH_REASONS:
            content = ""
        else:
            raise ValueError("No content or tool calls received from LLM")

    usage = getattr(response, "usage", None)
    stats: dict = {
        "provider_request_id": getattr(response, "id", None),
        "reasoning_tokens": getattr(
            getattr(usage, "completion_tokens_details", None), "reasoning_tokens", None
        ),
        "finish_reason": getattr(response.choices[0], "finish_reason", None),
        "prompt_tokens": _usage_value(usage, "prompt_tokens"),
        "completion_tokens": _usage_value(usage, "completion_tokens"),
        "response_ms": getattr(response, "_response_ms", 0),
        "response_cost": _usage_value(usage, "cost", None),
        "cached_tokens": _cached_tokens(usage),
        "cache_discount": _usage_value(usage, "cache_discount", None),
    }
    # A chain request can be answered by a model further down the list.
    served = getattr(response, "model", None)
    if served:
        stats["served_model"] = served
    reasoning_content = _extra(message).get("reasoning") or getattr(
        message, "reasoning_content", None
    )
    if reasoning_content:
        stats["reasoning_content"] = reasoning_content

    if stats["finish_reason"] in INCOMPLETE_FINISH_REASONS:
        raise IncompleteCompletionError(content.strip(), stats)
    return content.strip(), stats


def _provider_preferences(completion_kwargs: dict) -> dict | None:
    """Without ``require_parameters`` OpenRouter may route a schema-carrying request
    to a provider that ignores the schema, and the reply comes back as prose.
    """
    if "response_format" in completion_kwargs or "tools" in completion_kwargs:
        return {"require_parameters": True}
    return None


def _fallback_slugs(models: list[str] | None, selected_slug: str) -> list[str] | None:
    """OpenRouter walks ``models`` on any error and bills the one that answered,
    naming it in ``response.model``. The lead model must head the list.
    """
    if not models:
        return None
    slugs = [selected_slug]
    for name in models:
        with suppress(ValueError):
            slug = openrouter_slug(name)
            if slug not in slugs:
                slugs.append(slug)
    return slugs if len(slugs) > 1 else None


def _response_format_param(response_format: type[BaseModel] | None) -> dict | None:
    if response_format is None:
        return None
    # Strict structured outputs need `additionalProperties: false` on every object
    # and every key in `required`; pydantic's model_json_schema emits neither, so
    # this uses the SDK's own transformer, the one `.parse()` uses.
    return {
        "type": "json_schema",
        "json_schema": {
            "name": response_format.__name__,
            "strict": True,
            "schema": to_strict_json_schema(response_format),
        },
    }


def _reasoning_extra_body(
    selected_model_name: str,
    reasoning_effort: str | None,
    thinking_budget_tokens: int | None,
) -> dict[str, Any] | None:
    reasoning = reasoning_of(selected_model_name)
    effective_reasoning_effort = reasoning_effort
    if effective_reasoning_effort is None and reasoning.required:
        effective_reasoning_effort = "medium"

    if reasoning.adaptive is False and thinking_budget_tokens is not None:
        if thinking_budget_tokens in reasoning.budgets and thinking_budget_tokens > 0:
            return {"reasoning": {"max_tokens": thinking_budget_tokens}}
        return None

    if reasoning.adaptive is True and effective_reasoning_effort in reasoning.levels:
        effort = "high" if effective_reasoning_effort == "max" else effective_reasoning_effort
        return {"reasoning": {"effort": effort}}
    return None


def call_llm(
    input_text: str,
    system_prompt: str | None = None,
    model: str | None = None,
    response_format: type[BaseModel] | None = None,
    request_kwargs: dict | None = None,
    messages: list[dict[str, Any]] | None = None,
    tools: list[dict[str, Any]] | None = None,
    reasoning_effort: str | None = None,
    thinking_budget_tokens: int | None = None,
    model_spec: ModelSpec | None = None,
    max_tokens: int = 5000,
    fallback_models: list[str] | None = None,
    retry_deadline: float = RETRY_DEADLINE_BACKGROUND,
    max_attempts: int | None = None,
) -> tuple[str, dict]:
    if any(
        is_decision_model(name)
        for name in [
            model or "",
            model_spec.model_id if model_spec else "",
            *(fallback_models or []),
        ]
    ):
        raise ValueError("Decision models require typed questions through the decision transport.")
    if request_kwargs is None:
        request_kwargs = {}

    if messages is None:
        messages = []
        if system_prompt:
            messages.append({"role": "system", "content": system_prompt})
        messages.append({"role": "user", "content": input_text})
    else:
        messages = [
            m
            for m in messages
            if not (m.get("content") is None and m.get("role") in ("system", "user"))
        ]

    try:
        if model_spec is not None:
            if model_spec.params:
                request_kwargs = {**model_spec.params, **request_kwargs}
            client, selected_model, provider = _model_spec_client_and_name(model_spec)
            selected_model_name = normalize_model_name(model_spec.model_id)

            completion_kwargs = {
                "model": selected_model,
                "messages": messages,
                "max_tokens": effective_max_tokens(selected_model_name, max_tokens),
            }
            if "max_tokens" in request_kwargs:
                cap = request_kwargs.pop("max_tokens")
                if cap is not None:
                    completion_kwargs["max_tokens"] = int(cap)
            formatted_response = _response_format_param(response_format)
            if formatted_response:
                completion_kwargs["response_format"] = formatted_response
            if tools:
                completion_kwargs["tools"] = tools
            extra_body = {"usage": {"include": True}}
            reasoning_body = _reasoning_extra_body(
                selected_model_name,
                reasoning_effort,
                thinking_budget_tokens,
            )
            if reasoning_body and provider == "openrouter":
                extra_body.update(reasoning_body)
            if provider == "openrouter":
                preferences = _provider_preferences(completion_kwargs)
                if preferences:
                    extra_body["provider"] = preferences
            if _is_openrouter(client):
                completion_kwargs["extra_body"] = extra_body

            response = _do_openai_completion(
                client, completion_kwargs, request_kwargs, retry_deadline, max_attempts
            )
            return _extract_llm_response(response)

        selected_model_name = normalize_model_name(model) if model else _get_default_model()
        selected_model = openrouter_slug(selected_model_name)
        client = openrouter_client()

        completion_kwargs: dict = {
            "model": selected_model,
            "messages": messages,
            "max_tokens": effective_max_tokens(selected_model_name, max_tokens),
            "extra_body": {"usage": {"include": True}},
        }
        formatted_response = _response_format_param(response_format)
        if formatted_response:
            completion_kwargs["response_format"] = formatted_response

        if tools:
            completion_kwargs["tools"] = tools

        if "max_tokens" in request_kwargs:
            completion_kwargs["max_tokens"] = request_kwargs["max_tokens"]
            request_kwargs = {
                key: value for key, value in request_kwargs.items() if key != "max_tokens"
            }

        reasoning_body = _reasoning_extra_body(
            selected_model_name,
            reasoning_effort,
            thinking_budget_tokens,
        )
        if reasoning_body:
            completion_kwargs["extra_body"].update(reasoning_body)

        preferences = _provider_preferences(completion_kwargs)
        if preferences:
            completion_kwargs["extra_body"]["provider"] = preferences
        chain = _fallback_slugs(fallback_models, selected_model)
        if chain:
            completion_kwargs["extra_body"]["models"] = chain

        response = _do_openai_completion(
            client, completion_kwargs, request_kwargs, retry_deadline, max_attempts
        )
        return _extract_llm_response(response)

    except (IncompleteCompletionError, SoftTimeLimitExceeded):
        raise
    except Exception as e:
        raise RuntimeError(f"Error calling LLM: {e}") from e


def _tool_completion_kwargs(
    messages: list[dict[str, Any]],
    tools: list[dict[str, Any]],
    model: str | None,
    max_tokens: int,
    fallback_models: list[str] | None,
) -> tuple[dict, str]:
    selected_model_name = normalize_model_name(model) if model else _get_default_model()
    selected = openrouter_slug(selected_model_name)
    completion_kwargs: dict = {
        "model": selected,
        "messages": messages,
        "max_tokens": effective_max_tokens(selected_model_name, max_tokens),
    }
    # An empty tools array is a 400 on some providers.
    if tools:
        completion_kwargs["tools"] = tools
    extra_body: dict = {"usage": {"include": True}, "provider": {"require_parameters": True}}
    reasoning_body = _reasoning_extra_body(selected_model_name, None, None)
    if reasoning_body:
        extra_body.update(reasoning_body)
    chain = _fallback_slugs(fallback_models, selected)
    if chain:
        extra_body["models"] = chain
    completion_kwargs["extra_body"] = extra_body
    return completion_kwargs, selected


def _tool_call_stats(
    usage: Any, served_model: Any, selected: str, response_ms: Any, generation: Any
) -> dict:
    return {
        # OpenRouter's generation id: what the call cost, once usage did not say.
        "provider_request_id": generation,
        "prompt_tokens": _usage_value(usage, "prompt_tokens"),
        "completion_tokens": _usage_value(usage, "completion_tokens"),
        "response_ms": response_ms or 0,
        "response_cost": _usage_value(usage, "cost", None),
        "cached_tokens": _cached_tokens(usage),
        "served_model": served_model or selected,
    }


def call_llm_tools(
    messages: list[dict[str, Any]],
    tools: list[dict[str, Any]],
    model: str | None = None,
    max_tokens: int = 4000,
    fallback_models: list[str] | None = None,
    retry_deadline: float = RETRY_DEADLINE_BACKGROUND,
    max_attempts: int | None = None,
    tool_choice: Literal["auto", "required"] = "auto",
    on_progress: Callable[[str, str], None] | None = None,
) -> tuple[str, list[dict[str, Any]], dict]:
    """One tool-calling completion returning ``(text, tool_calls, stats)``.

    :func:`call_llm` drops ``tool_calls`` whenever the model also returns text;
    this keeps both, which agentic loops need when a model narrates while
    proposing calls. With ``on_progress`` the completion is streamed and sent once: it
    receives the text and the reasoning the provider shows so far, and ``stats["thinking"]``
    holds all of it.
    """
    if on_progress is not None:
        text, tool_calls, stats = stream_llm_tools(
            messages,
            tools,
            model,
            fallback_models,
            max_tokens=max_tokens,
            tool_choice=tool_choice,
            deadline=retry_deadline,
            on_reasoning=on_progress,
        )
        stats["assistant_message"] = {
            "role": "assistant",
            "content": text,
            "tool_calls": tool_calls,
            # The provider needs these back unchanged with the reply's tool results.
            **(
                {"reasoning_details": stats["reasoning_details"]}
                if stats["reasoning_details"]
                else {}
            ),
        }
        return text, tool_calls, stats
    completion_kwargs, selected = _tool_completion_kwargs(
        messages, tools, model, max_tokens, fallback_models
    )
    if tools:
        completion_kwargs["tool_choice"] = tool_choice
    try:
        response = _do_openai_completion(
            _provider_client("openrouter"), completion_kwargs, {}, retry_deadline, max_attempts
        )
    except SoftTimeLimitExceeded:
        raise
    except Exception as e:
        raise RuntimeError(f"Error calling LLM: {e}") from e

    message = response.choices[0].message
    text = (message.content or "").strip()
    tool_calls = [tc.model_dump() for tc in (getattr(message, "tool_calls", None) or [])]
    stats = _tool_call_stats(
        getattr(response, "usage", None),
        getattr(response, "model", None),
        selected,
        getattr(response, "_response_ms", 0),
        getattr(response, "id", None),
    )
    stats["finish_reason"] = getattr(response.choices[0], "finish_reason", None)
    stats["provider_id"] = getattr(response, "id", None)
    stats["assistant_message"] = message.model_dump(exclude_none=True)
    if stats["finish_reason"] in INCOMPLETE_FINISH_REASONS:
        raise IncompleteCompletionError(text, stats)
    return text, tool_calls, stats


# Fields of a streamed reasoning detail that arrive in pieces.
_REASONING_TEXT = ("text", "summary", "data")


STREAM_MAX_TOKENS = 8000


def _shown_reasoning(details) -> str:
    """The reasoning a provider streams in the clear: its summaries, else its text. Encrypted
    records hold neither."""
    parts = [detail.get("summary") or detail.get("text") or "" for detail in details]
    return "\n\n".join(part for part in parts if isinstance(part, str) and part)


@lru_cache(maxsize=1)
def _stream_client() -> OpenAI:
    """A synchronous client, shared by the worker's threads: a stream's ``on_progress``
    then runs in the caller's thread and may use the ORM."""
    provider = PROVIDERS["openrouter"]
    api_key = provider.key()
    if not api_key:
        raise RuntimeError(f"{provider.key_env} is required for LLM completions")
    return OpenAI(
        api_key=api_key,
        base_url=provider.base_url,
        default_headers=provider.headers or None,
        timeout=_REQUEST_TIMEOUT,
        max_retries=_SDK_RETRIES,
    )


def stream_llm_tools(
    messages: list[dict[str, Any]],
    tools: list[dict[str, Any]],
    model: str | None = None,
    fallback_models: list[str] | None = None,
    on_progress: Callable[[str, list[dict]], None] | None = None,
    *,
    max_tokens: int = STREAM_MAX_TOKENS,
    tool_choice: Literal["auto", "required"] | None = None,
    deadline: float = RETRY_DEADLINE_BACKGROUND,
    on_reasoning: Callable[[str, str], None] | None = None,
) -> tuple[str, list[dict[str, Any]], dict]:
    """:func:`call_llm_tools`, streamed. ``on_progress`` receives the text so far and the
    tool calls as far as they are written; ``on_reasoning`` the text and the reasoning the
    provider shows so far. An exception either raises ends the stream and propagates. The
    provider bills a stream that started, also one cut off later: it is charged once its
    generation is priced.

    Never retried: a stream that started may already be billed.
    """
    completion_kwargs, selected = _tool_completion_kwargs(
        messages, tools, model, max_tokens, fallback_models
    )
    completion_kwargs |= {"stream": True, "stream_options": {"include_usage": True}}
    if tools and tool_choice:
        completion_kwargs["tool_choice"] = tool_choice
    text, calls, usage, served, finish, generation = "", {}, None, None, None, None
    reasoning: dict[tuple, dict] = {}
    started = time.monotonic()
    expired = threading.Event()
    try:
        with _stream_client().chat.completions.create(**completion_kwargs) as stream:
            # A provider can keep the stream open with keep-alive comments and no chunk:
            # the deadline closes it from outside the wait.
            timer = threading.Timer(deadline, lambda: (expired.set(), stream.close()))
            timer.daemon = True
            timer.start()
            try:
                for chunk in stream:
                    usage, served = chunk.usage or usage, chunk.model or served
                    if generation is None and chunk.id:
                        generation = chunk.id
                    for choice in chunk.choices:
                        finish = choice.finish_reason or finish
                        text += choice.delta.content or ""
                        for part in _extra(choice.delta).get("reasoning_details") or []:
                            # Fragments of one record share its index; records without one
                            # stay apart by their id.
                            position = part.get("index")
                            identity = position if position is not None else part.get("id")
                            detail = reasoning.setdefault((identity, part.get("type")), {})
                            for key, value in part.items():
                                streamed = key in _REASONING_TEXT and isinstance(value, str)
                                detail[key] = detail.get(key, "") + value if streamed else value
                        for piece in choice.delta.tool_calls or []:
                            call = calls.setdefault(
                                piece.index,
                                {
                                    "id": "",
                                    "type": "function",
                                    "function": {"name": "", "arguments": ""},
                                },
                            )
                            call["id"] = piece.id or call["id"]
                            if piece.function is not None:
                                call["function"]["name"] += piece.function.name or ""
                                call["function"]["arguments"] += piece.function.arguments or ""
                        if on_progress is not None:
                            on_progress(text, [calls[index] for index in sorted(calls)])
                        if on_reasoning is not None:
                            on_reasoning(text, _shown_reasoning(reasoning.values()))
                if expired.is_set():
                    raise CompletionDeadlineExceededError(
                        f"Completion deadline exceeded after {deadline:g}s"
                    )
            except Exception:
                if expired.is_set():
                    raise CompletionDeadlineExceededError(
                        f"Completion deadline exceeded after {deadline:g}s"
                    ) from None
                raise
            finally:
                timer.cancel()
    except openai.OpenAIError as exc:
        raise RuntimeError(f"Error calling LLM: {exc}") from exc
    finally:
        if generation is not None:
            _settle(SimpleNamespace(id=generation, usage=usage, model=served), selected)
    text, tool_calls = text.strip(), [calls[index] for index in sorted(calls)]
    stats = _tool_call_stats(
        usage, served, selected, (time.monotonic() - started) * 1000, generation
    )
    stats["finish_reason"] = finish
    # The provider needs these back unchanged with the reply's tool results.
    stats["reasoning_details"] = list(reasoning.values())
    if shown := _shown_reasoning(reasoning.values()):
        stats["thinking"] = shown
    if stats["finish_reason"] in INCOMPLETE_FINISH_REASONS:
        raise IncompleteCompletionError(text, stats)
    return text, tool_calls, stats


def try_json_parsing(json_data: str):
    res = json_repair.loads(json_data)
    if not res:
        raise ValueError(f"Failed to parse JSON: {json_data}")
    return res