BerriAI/litellm · critical · HTTPException

Missing Authorization header

Error message

Missing Authorization header

What it means

A pre-flight guard in OpenAI fine-tuning job creation: get_openai_client() returns None when no usable client can be constructed (no api_key passed, no OPENAI_API_KEY env var, no custom client, and no default api_base that permits an anonymous client). When it returns None, this ValueError stops the call before touching the network. It is purely a local configuration error.

Source

Thrown at cookbook/mock_guardrail_server/mock_bedrock_guardrail_server.py:177

# Authentication
# ============================================================================


async def verify_bearer_token(authorization: Optional[str] = Header(None)) -> str:
    """
    Verify the Bearer token from the Authorization header.

    Args:
        authorization: The Authorization header value

    Returns:
        The token if valid

    Raises:
        HTTPException: If token is missing or invalid
    """
    if authorization is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Missing Authorization header",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # Check if it's a Bearer token
    parts = authorization.split()
    print(f"parts: {parts}")
    if len(parts) != 2 or parts[0].lower() != "bearer":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid Authorization header format. Expected: Bearer <token>",
            headers={"WWW-Authenticate": "Bearer"},
        )

    token = parts[1]

    # Verify token

View on GitHub (pinned to 6c2dcb801b)

Solutions

  1. Set OPENAI_API_KEY in the environment before running the script.
  2. Or pass api_key=... directly to create_fine_tuning_job.
  3. Or pass a prebuilt OpenAI(...) client via the client= argument.
  4. For Azure, ensure api_base/api_version route to an Azure client so the OpenAI-key requirement is replaced correctly.

Example fix

# before
job = litellm.create_fine_tuning_job(model="gpt-4o-mini-2024-07-18", training_file="file-abc")

# after
job = litellm.create_fine_tuning_job(
    model="gpt-4o-mini-2024-07-18",
    training_file="file-abc",
    api_key=os.environ["OPENAI_API_KEY"],
)
Defensive patterns

Strategy: validation

Validate before calling

import os

def has_openai_credentials(api_key: str | None, client: object | None) -> bool:
    return bool(api_key or client or os.environ.get("OPENAI_API_KEY"))

if not has_openai_credentials(api_key, client):
    raise SystemExit("OPENAI_API_KEY missing; refusing to start fine-tuning")

Try / catch

try:
    job = litellm.create_fine_tuning_job(model=m, training_file=f)
except ValueError as e:
    if "not initialized" in str(e):
        job = litellm.create_fine_tuning_job(model=m, training_file=f, api_key=os.environ["OPENAI_API_KEY"])
    else:
        raise

Prevention

When it happens

Trigger: Calling litellm.create_fine_tuning_job() without api_key, without a custom OpenAI client, and without OPENAI_API_KEY set in the environment (or via the secret manager).

Common situations: Scripts that previously relied on a globally set key in an interactive shell but run in fresh CI containers; notebooks where os.environ was set after import; Azure workflows that pass azure creds but no OpenAI key while the default OpenAI endpoint is still targeted.

Related errors


AI-assisted analysis of BerriAI/litellm@6c2dcb801b (2026-08-15). Data as JSON: /api/errors/1bebc815a2686cf8. Report an issue: GitHub.