Skip to content

openai_compat_backend

openai_compat_backend

Generic OpenAI-compatible HTTP execution for profile-driven instruments.

The backend speaks the standard OpenAI chat/completions protocol and works against any compatible HTTP service, including hosted and local servers.

Usage is internal only — it is constructed by marianne.daemon.baton.backend_pool._build_openai_family_backend when dispatching an HttpProfile whose schema_family is openai.

Key design decisions: - Extends Backend ABC with HttpxClientMixin for lazy httpx client lifecycle. - Model is specified per-request, allowing per-sheet instrument overrides. - Rate limit detection from HTTP 429 status and Retry-After header. - Token usage extracted from the standard OpenAI usage response field. - Free-tier model support (no cost for many models).

Security: API keys are NEVER logged. The key is read from environment and passed only in the Authorization header. The logging infrastructure uses SENSITIVE_PATTERNS to automatically redact fields containing 'api_key', 'token', 'secret', etc.

Classes

OpenAICompatibleBackend

OpenAICompatibleBackend(model, base_url, *, api_key_env=None, max_tokens=16384, temperature=0.7, timeout_seconds=300.0, endpoint='/chat/completions', response_format=None, loaded_profile=None)

Bases: HttpxClientMixin, Backend

Run prompts through a profile-selected OpenAI-compatible API.

Connection details come from an instrument profile. The executor carries no provider-specific endpoint, model, authentication, or headers.

Example usage::

backend = OpenAICompatibleBackend(
    model="minimax/minimax-m1-80k",
    base_url="https://openrouter.ai/api/v1",
    api_key_env="OPENROUTER_API_KEY",
)
result = await backend.execute("Explain quicksort")

Initialize a profile-selected OpenAI-compatible transport.

Parameters:

Name Type Description Default
model str

Model ID understood by the selected endpoint.

required
base_url str

API base URL (without endpoint path).

required
api_key_env str | None

Optional environment variable containing an API key.

None
max_tokens int

Maximum tokens for response.

16384
temperature float

Sampling temperature (0.0-2.0).

0.7
timeout_seconds float

Maximum time for API request.

300.0
endpoint str

Profile-selected OpenAI chat-completions endpoint.

'/chat/completions'
response_format dict[str, Any] | None

Opt-in structured-output object from the instrument profile (None = omit the key; the legacy payload). Validated here; per-sheet overrides come through set_response_format().

None
Source code in src/marianne/execution/instruments/openai_compat_backend.py
def __init__(
    self,
    model: str,
    base_url: str,
    *,
    api_key_env: str | None = None,
    max_tokens: int = 16384,
    temperature: float = 0.7,
    timeout_seconds: float = 300.0,
    endpoint: str = "/chat/completions",
    response_format: dict[str, Any] | None = None,
    loaded_profile: InstrumentProfile | None = None,
) -> None:
    """Initialize a profile-selected OpenAI-compatible transport.

    Args:
        model: Model ID understood by the selected endpoint.
        base_url: API base URL (without endpoint path).
        api_key_env: Optional environment variable containing an API key.
        max_tokens: Maximum tokens for response.
        temperature: Sampling temperature (0.0-2.0).
        timeout_seconds: Maximum time for API request.
        endpoint: Profile-selected OpenAI chat-completions endpoint.
        response_format: Opt-in structured-output object from the
            instrument profile (None = omit the key; the legacy
            payload). Validated here; per-sheet overrides come through
            set_response_format().
    """
    if not model:
        raise ValueError("model must be a non-empty string")
    if max_tokens < 1:
        raise ValueError(f"max_tokens must be >= 1, got {max_tokens}")
    if timeout_seconds <= 0:
        raise ValueError(f"timeout_seconds must be > 0, got {timeout_seconds}")

    self.model = model
    self.api_key_env = api_key_env
    self.max_tokens = max_tokens
    self.temperature = temperature
    self.timeout_seconds = timeout_seconds
    self.endpoint = endpoint
    self._loaded_profile = loaded_profile.model_copy(deep=True) if loaded_profile else None
    self._default_response_format: dict[str, Any] | None = (
        validate_openai_response_format(response_format)
        if response_format is not None
        else None
    )
    self._response_format: dict[str, Any] | None = self._default_response_format
    self._working_directory: Path | None = None

    # Read API key from environment (may be None — checked at execute time)
    self._api_key: str | None = os.environ.get(api_key_env) if api_key_env else None

    # Error classifier for rate limit wait extraction
    self._error_classifier = ErrorClassifier()

    # Per-sheet overrides — saved originals for clear_overrides()
    self._saved_model: str | None = None
    self._saved_temperature: float | None = None
    self._saved_max_tokens: int | None = None
    self._has_overrides: bool = False

    # Real-time output logging (set per-sheet by the musician)
    self._stdout_log_path: Path | None = None
    self._stderr_log_path: Path | None = None

    # Preamble and extensions for prompt injection
    self._preamble: str | None = None
    self._prompt_extensions: list[str] = []

    # The generic transport adds only protocol-required headers. Profiles
    # choose authentication; provider-specific metadata belongs outside it.
    headers: dict[str, str] = {"Content-Type": "application/json"}
    if self._api_key:
        headers["Authorization"] = f"Bearer {self._api_key}"

    # HTTP client lifecycle via shared mixin
    self._init_httpx_mixin(
        base_url.rstrip("/"),
        timeout_seconds,
        connect_timeout=10.0,
        headers=headers,
    )
Attributes
name property
name

Human-readable backend name including model.

Methods:
effort_refusal
effort_refusal(level, *, schema_mode, model=None)

Why this instrument cannot run a sheet at level (None = it can).

Judged against the loaded profile's effort: block (delivery body_field) for model, or this backend's model when None. A backend built without a profile carries no mapping.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
def effort_refusal(
    self, level: str, *, schema_mode: bool, model: str | None = None,
) -> str | None:
    """Why this instrument cannot run a sheet at ``level`` (None = it can).

    Judged against the loaded profile's ``effort:`` block (delivery
    ``body_field``) for ``model``, or this backend's model when None.
    A backend built without a profile carries no mapping.
    """
    if self._loaded_profile is None:
        return (
            "declares no reasoning-effort mapping (the profile's effort: "
            f"block), so instrument_config.effort {level!r} cannot be "
            "applied; accepted levels: none"
        )
    return self._loaded_profile.effort_refusal(
        level, model=model or self.model, schema_mode=schema_mode,
    )
set_api_key
set_api_key(api_key)

Set a key supplied by the runtime keyring, if one is available.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
def set_api_key(self, api_key: str | None) -> None:
    """Set a key supplied by the runtime keyring, if one is available."""
    self._api_key = api_key
    if api_key:
        self._httpx_headers["Authorization"] = f"Bearer {api_key}"
    else:
        self._httpx_headers.pop("Authorization", None)
apply_overrides
apply_overrides(overrides)

Apply per-sheet overrides for the next execution.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
def apply_overrides(self, overrides: dict[str, object]) -> None:
    """Apply per-sheet overrides for the next execution."""
    if not overrides:
        return
    self._saved_model = self.model
    self._saved_temperature = self.temperature
    self._saved_max_tokens = self.max_tokens
    self._has_overrides = True
    if "model" in overrides:
        self.model = str(overrides["model"])
    if "temperature" in overrides:
        self.temperature = float(overrides["temperature"])  # type: ignore[arg-type]
    if "max_tokens" in overrides:
        self.max_tokens = int(overrides["max_tokens"])  # type: ignore[call-overload]
clear_overrides
clear_overrides()

Restore original backend parameters after per-sheet execution.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
def clear_overrides(self) -> None:
    """Restore original backend parameters after per-sheet execution."""
    # Per-sheet response_format never survives release into the shared
    # HTTP singleton (same carryover class as F-150's model override):
    # always restore the profile default, even when no other override
    # was applied.
    self._response_format = self._default_response_format
    # W-F3: preamble/prompt_extensions are per-sheet prompt bytes — a
    # prior sheet's healing-preamble evidence must never survive
    # release into the next sheet's outbound prompt on this shared
    # singleton (sequential smear, reachable with zero concurrency).
    self._preamble = None
    self._prompt_extensions = []
    if not self._has_overrides:
        return
    self.model = self._saved_model  # type: ignore[assignment]
    self.temperature = self._saved_temperature  # type: ignore[assignment]
    self.max_tokens = self._saved_max_tokens  # type: ignore[assignment]
    self._saved_model = None
    self._saved_temperature = None
    self._saved_max_tokens = None
    self._has_overrides = False
set_preamble
set_preamble(preamble)

Set the dynamic preamble for the next execution.

Direct-use contract only: the pooled dispatch path carries the per-attempt preamble request-locally (SheetRequestState) — see Backend.set_preamble. On this shared HTTP singleton a mutable preamble is the W-F3 sequential-smear seam; clear_overrides() resets it.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
def set_preamble(self, preamble: str | None) -> None:
    """Set the dynamic preamble for the next execution.

    Direct-use contract only: the pooled dispatch path carries the
    per-attempt preamble request-locally (``SheetRequestState``) — see
    ``Backend.set_preamble``. On this shared HTTP singleton a mutable
    preamble is the W-F3 sequential-smear seam; ``clear_overrides()``
    resets it.
    """
    self._preamble = preamble
set_response_format
set_response_format(response_format)

Set an opt-in structured-output response_format for this sheet.

Direct-use contract only (exclusively-owned backends, tests, and the adapter's capability probe): the pooled dispatch path resolves the sheet's value once and carries it request-locally on SheetRequestState — never through this mutable slot, which is the W-F1/W-F2 transfer seam on the shared HTTP singleton. The value is validated by the shared wire-contract validator — invalid shapes raise ValueError. clear_overrides() restores the profile default at release.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
def set_response_format(
    self, response_format: dict[str, Any] | None
) -> None:
    """Set an opt-in structured-output response_format for this sheet.

    Direct-use contract only (exclusively-owned backends, tests, and
    the adapter's capability probe): the pooled dispatch path resolves
    the sheet's value once and carries it request-locally on
    ``SheetRequestState`` — never through this mutable slot, which is
    the W-F1/W-F2 transfer seam on the shared HTTP singleton. The
    value is validated by the shared wire-contract validator — invalid
    shapes raise ValueError. ``clear_overrides()`` restores the
    profile default at release.
    """
    self._response_format = (
        validate_openai_response_format(response_format)
        if response_format is not None
        else None
    )
set_prompt_extensions
set_prompt_extensions(extensions)

Set prompt extensions for the next execution.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
def set_prompt_extensions(self, extensions: list[str]) -> None:
    """Set prompt extensions for the next execution."""
    self._prompt_extensions = [e for e in extensions if e.strip()]
set_output_log_path
set_output_log_path(path)

Set base path for real-time output logging.

Parameters:

Name Type Description Default
path Path | None

Base path for log files (without extension), or None to disable.

required
Source code in src/marianne/execution/instruments/openai_compat_backend.py
def set_output_log_path(self, path: Path | None) -> None:
    """Set base path for real-time output logging.

    Args:
        path: Base path for log files (without extension), or None to disable.
    """
    if path is None:
        self._stdout_log_path = None
        self._stderr_log_path = None
    else:
        self._stdout_log_path = path.with_suffix(".stdout.log")
        self._stderr_log_path = path.with_suffix(".stderr.log")
execute async
execute(prompt, *, timeout_seconds=None, request=None)

Execute a prompt via the selected OpenAI-compatible API.

Sends a chat completion request and returns the generic response.

Parameters:

Name Type Description Default
prompt str

The prompt to send.

required
timeout_seconds float | None

Per-call HTTP timeout override for direct calls. A resolved sheet request uses its own HTTP timeout, falling back to the profile default when unset. Connect timeout is capped at ten seconds within that per-request timeout.

None
request SheetRequestState | None

Per-sheet state resolved once at dispatch. When provided, EVERY payload field it carries is request-local (W-F1/W-F2/W-F3): response_format applies its tri-state against the profile default, never the mutable slot another dispatch may have written; preamble/extensions come from the request alone. None preserves the legacy direct-call behavior of the mutable setters.

None

Returns:

Type Description
ExecutionResult

ExecutionResult with API response and metadata.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
async def execute(
    self,
    prompt: str,
    *,
    timeout_seconds: float | None = None,
    request: SheetRequestState | None = None,
) -> ExecutionResult:
    """Execute a prompt via the selected OpenAI-compatible API.

    Sends a chat completion request and returns the generic response.

    Args:
        prompt: The prompt to send.
        timeout_seconds: Per-call HTTP timeout override for direct calls.
            A resolved sheet request uses its own HTTP timeout, falling
            back to the profile default when unset. Connect timeout is
            capped at ten seconds within that per-request timeout.
        request: Per-sheet state resolved once at dispatch. When
            provided, EVERY payload field it carries is request-local
            (W-F1/W-F2/W-F3): ``response_format`` applies its tri-state
            against the profile default, never the mutable slot another
            dispatch may have written; preamble/extensions come from the
            request alone. ``None`` preserves the legacy direct-call
            behavior of the mutable setters.

    Returns:
        ExecutionResult with API response and metadata.
    """
    if request is not None and request.http_timeout_resolved:
        request_timeout = (
            request.http_timeout_seconds
            if request.http_timeout_seconds is not None
            else self.timeout_seconds
        )
    else:
        request_timeout = (
            timeout_seconds if timeout_seconds is not None
            else self.timeout_seconds
        )
    http_timeout = httpx.Timeout(
        request_timeout, connect=min(10.0, request_timeout)
    )

    start_time = time.monotonic()
    started_at = utc_now()
    requested_model = (
        request.model if request is not None and request.model else self.model
    )
    requested_max_tokens = self._cap_max_tokens(
        request.max_tokens if request is not None and request.max_tokens is not None
        else self.max_tokens,
        requested_model,
    )
    requested_temperature = (
        request.temperature if request is not None and request.temperature is not None
        else self.temperature
    )

    _logger.debug(
        "openai_compatible_execute_start",
        model=requested_model,
        prompt_length=len(prompt),
        max_tokens=requested_max_tokens,
    )

    # Check API key before making request
    if self.api_key_env and not self._api_key:
        duration = time.monotonic() - start_time
        msg = (
            f"API key not found in environment variable: {self.api_key_env}. "
            f"Set {self.api_key_env} or configure the instrument keyring."
        )
        _logger.error(
            "configuration_error",
            api_key_env=self.api_key_env,
        )
        self._write_log_file(self._stderr_log_path, msg)
        return ExecutionResult(
            success=False,
            exit_code=1,
            stdout="",
            stderr=msg,
            duration_seconds=duration,
            started_at=started_at,
            error_type="configuration",
            error_message=msg,
            model=requested_model,
        )

    # Request-local per-sheet state (W-F1/W-F2/W-F3): the pooled HTTP
    # singleton is shared by concurrent sheets across jobs, so the
    # values that build THIS payload come from the dispatch-resolved
    # request — never from mutable attributes another dispatch may
    # have written between this sheet's dispatch and its payload build.
    if request is not None:
        response_format = (
            self._default_response_format
            if request.response_format is RESPONSE_FORMAT_UNSET
            else request.response_format
        )
        preamble = request.preamble
        prompt_extensions = request.prompt_extensions
    else:
        # Legacy direct-call path: exclusively-owned backends and
        # direct callers that configure the setters keep their
        # documented behavior.
        response_format = self._response_format
        preamble = self._preamble
        prompt_extensions = tuple(self._prompt_extensions)

    assembled_prompt = self._assemble_prompt(
        prompt, preamble, prompt_extensions
    )

    payload: dict[str, Any] = {
        "model": requested_model,
        "messages": [{"role": "user", "content": assembled_prompt}],
        "max_tokens": requested_max_tokens,
        "temperature": requested_temperature,
    }
    # Opt-in structured output: forwarded exactly as validated — the
    # provider, not this transport, owns the object's semantics. Absent
    # configuration keeps the legacy four-key payload byte-identical.
    if response_format is not None:
        payload["response_format"] = response_format
    # Reasoning effort (GH #535): request-local like every other payload
    # field here; the profile's effort: block names the body path and the
    # native word. Unset keeps the legacy payload byte-identical.
    effort = request.effort if request is not None else None
    if effort is not None:
        refusal = self.effort_refusal(
            effort, schema_mode=response_format is not None, model=requested_model,
        )
        mapping = (
            self._loaded_profile.effort if self._loaded_profile is not None else None
        )
        if refusal is not None or mapping is None or self._loaded_profile is None:
            raise ValueError(
                f"instrument '{self.name}' {refusal}. Refusing to send the "
                "request at an effort it did not ask for"
            )
        payload = mapping.apply_to_body(
            payload,
            self._loaded_profile.native_effort(effort, model=requested_model),
        )

    guarded_client: httpx.AsyncClient | None = None
    expected = request.expected_route if request is not None else None
    try:
        if expected is not None:
            try:
                if expected.arm not in {"local", "remote"} or self._loaded_profile is None:
                    raise ValueError(
                        "guarded dispatch requires an observable HTTP profile"
                    )
                if expected.arm == "remote" and (
                    expected.transport_scheme != "https"
                    or not expected.effective_provider
                    or expected.profile_origin is None
                ):
                    raise ValueError(
                        "remote guarded dispatch requires a reviewed HTTPS provider profile"
                    )
                if self._loaded_profile.http is None or (
                    self._httpx_base_url != self._loaded_profile.http.base_url.rstrip("/")
                    or self.endpoint != self._loaded_profile.http.endpoint
                ):
                    raise ValueError("executor transport differs from its loaded profile")
                assert request is not None
                fresh = await asyncio.to_thread(
                    capture_resolved_instrument_route,
                    self._loaded_profile.name,
                    {"model": request.route_model_override,
                     "provider": request.route_provider_override},
                    now=utc_now(), arm=expected.arm,
                    loaded_profile=self._loaded_profile,
                )
                if route_identity(fresh) != route_identity(expected):
                    raise ValueError("reviewed route differs from current resolved route")
                if requested_model != fresh.effective_model:
                    raise ValueError("outbound model differs from resolved route")
                guarded_client = httpx.AsyncClient(
                    base_url=self._httpx_base_url,
                    timeout=self._httpx_timeout,
                    headers=self._httpx_headers if self._httpx_headers else None,
                    trust_env=False,
                    follow_redirects=False,
                    transport=httpx.AsyncHTTPTransport(retries=0),
                )
                client = guarded_client
                started_at = utc_now()
                if not 0 <= (started_at - fresh.resolved_at).total_seconds() <= (
                    ROUTE_DISPATCH_MAX_LEAD_SECONDS
                ):
                    raise ValueError(
                        "daemon route capture is out of the 60-second start window"
                    )
            except (OSError, ValueError) as exc:
                return self._route_refusal(str(exc), start_time, started_at, requested_model)
        else:
            client = await self._get_client()

        response = await client.post(
            self.endpoint,
            json=payload,
            timeout=http_timeout,
        )

        duration = time.monotonic() - start_time
        if expected is not None:
            if utc_now() < started_at:
                return self._route_refusal(
                    "completion clock precedes request start",
                    start_time, started_at, requested_model,
                )
            if 300 <= response.status_code < 400:
                return self._route_refusal(
                    "guarded HTTP redirect refused", start_time, started_at, requested_model,
                )

        # Handle rate limiting via HTTP status
        if response.status_code == 429:
            return self._handle_rate_limit(response, duration, started_at, requested_model)

        # Handle other HTTP errors
        if response.status_code >= 400:
            return self._handle_http_error(response, duration, started_at, requested_model)

        # Parse successful response
        data = response.json()
        return self._parse_success_response(
            data, duration, started_at, requested_model,
            json_mode=response_format is not None,
        )

    except httpx.ConnectError as e:
        duration = time.monotonic() - start_time
        _logger.error("openai_compatible_connection_error", error=str(e))
        self._write_log_file(self._stderr_log_path, str(e))
        return ExecutionResult(
            success=False,
            exit_code=503,
            stdout="",
            stderr=f"Connection error: {e}",
            duration_seconds=duration,
            started_at=started_at,
            error_type="connection",
            error_message=str(e),
            model=requested_model,
        )

    except httpx.TimeoutException as e:
        duration = time.monotonic() - start_time
        _logger.error(
            "openai_compatible_timeout",
            timeout_seconds=request_timeout,
            error=str(e),
        )
        self._write_log_file(self._stderr_log_path, str(e))
        return ExecutionResult(
            success=False,
            exit_code=408,
            stdout="",
            stderr=f"Timeout after {request_timeout}s: {e}",
            duration_seconds=duration,
            started_at=started_at,
            exit_reason="timeout",
            error_type="timeout",
            error_message=f"API timeout after {request_timeout}s: {e}",
            model=requested_model,
        )

    except Exception as e:
        duration = time.monotonic() - start_time
        _logger.exception(
            "openai_compatible_execute_error",
            model=requested_model,
            error=str(e),
        )
        self._write_log_file(self._stderr_log_path, str(e))
        raise
    finally:
        if guarded_client is not None:
            await guarded_client.aclose()
health_check async
health_check()

Check if the selected API is reachable and authenticated.

Uses the /models endpoint (lightweight, no token consumption) to verify connectivity and authentication.

Returns:

Type Description
bool

True if healthy, False otherwise.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
async def health_check(self) -> bool:
    """Check if the selected API is reachable and authenticated.

    Uses the /models endpoint (lightweight, no token consumption)
    to verify connectivity and authentication.

    Returns:
        True if healthy, False otherwise.
    """
    if self.api_key_env and not self._api_key:
        _logger.warning(
            "health_check_failed",
            error_type="MissingAPIKey",
            error=f"No API key configured — set {self.api_key_env}",
        )
        return False

    try:
        client = await self._get_client()
        response = await client.get("/models", timeout=10.0)
        if response.status_code == 200:
            return True
        _logger.warning(
            "openai_compatible_health_check_failed",
            status_code=response.status_code,
        )
        return False
    except (httpx.HTTPError, OSError, ValueError) as e:
        _logger.warning(
            "openai_compatible_health_check_error",
            error=str(e),
            error_type=type(e).__name__,
        )
        return False
availability_check async
availability_check()

Check if the backend can be initialized without consuming API quota.

Verifies that the API key is present and the httpx client can be created. Does NOT make any HTTP requests. Client initialization exceptions log openai_compatible_initialization_failed at WARNING and return False. A missing required API key returns False before attempting initialization.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
async def availability_check(self) -> bool:
    """Check if the backend can be initialized without consuming API quota.

    Verifies that the API key is present and the httpx client can be
    created. Does NOT make any HTTP requests.
    Client initialization exceptions log
    ``openai_compatible_initialization_failed`` at WARNING and return False.
    A missing required API key returns False before attempting initialization.
    """
    if self.api_key_env and not self._api_key:
        return False
    try:
        await self._get_client()
        return True
    except Exception:  # noqa: BLE001 — initialization failure marks the backend unavailable
        _logger.warning("openai_compatible_initialization_failed", exc_info=True)
        return False
close async
close()

Close HTTP client and release resources.

Source code in src/marianne/execution/instruments/openai_compat_backend.py
async def close(self) -> None:
    """Close HTTP client and release resources."""
    await self._close_httpx_client()

Functions: