openai_compat.py 1.04 KB
"""
Compatibility helpers for OpenAI-compatible providers.

These helpers keep the project friendly to local gateways such as Ollama,
where an API key may be intentionally left empty.
"""

from __future__ import annotations

from typing import Any, Optional

from openai import OpenAI


def coalesce_none(*values):
    """Return the first value that is not None, allowing empty strings."""
    for value in values:
        if value is not None:
            return value
    return None


def normalize_openai_api_key(api_key: Optional[str]) -> str:
    """
    Normalize an API key for the OpenAI Python client.

    The OpenAI client rejects `None`, but accepts an empty string. That makes
    empty keys workable for local OpenAI-compatible services that do not
    require authentication.
    """
    return "" if api_key is None else api_key


def create_openai_client(api_key: Optional[str], **kwargs: Any) -> OpenAI:
    """Create an OpenAI-compatible client that tolerates empty API keys."""
    return OpenAI(api_key=normalize_openai_api_key(api_key), **kwargs)