BerriAI/litellm · error · ValueError

OpenAI client is not initialized. Make sure api_key is…

Error message

OpenAI client is not initialized. Make sure api_key is passed or OPENAI_API_KEY is set in the environment.

What it means

litellm's OpenAI fine-tuning job creation path first builds (or accepts) an OpenAI client via get_openai_client; if that step yields no client (None) it raises this ValueError. In practice the None result means no usable credentials/configuration: no api_key argument and no OPENAI_API_KEY environment fallback to construct an OpenAI() SDK client from.

Solutions

  1. Pass api_key explicitly to create_fine_tuning_job, or pass a pre-built openai.OpenAI client via client=
  2. Export OPENAI_API_KEY in the runtime environment (shell profile, .env loaded before import, CI secret, docker -e)
  3. Set litellm.api_key = 'sk-...' once at startup if you use module-level config
  4. If you intentionally pass client=, make sure it is an instantiated OpenAI()/AzureOpenAI() object, not None

Example fix

# before
job = litellm.create_fine_tuning_job(model="gpt-4o-2024-08-06", training_file=file_id)
# ValueError: OpenAI client is not initialized...

# after
job = litellm.create_fine_tuning_job(
    model="gpt-4o-2024-08-06",
    training_file=file_id,
    api_key=os.environ["OPENAI_API_KEY"],
)
Defensive patterns

Strategy: validation

Validate before calling

import os

api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
    raise SystemExit("OPENAI_API_KEY not set - cannot create fine-tuning jobs")

job = litellm.create_fine_tuning_job(
    model="gpt-4o-2024-08-06", training_file=file_id, api_key=api_key
)

Type guard

def can_run_finetuning(api_key, client) -> bool:
    """True when a fine-tuning call has credentials or a ready client."""
    import os
    return bool(api_key or client is not None or os.getenv("OPENAI_API_KEY"))

Try / catch

try:
    job = litellm.create_fine_tuning_job(model=m, training_file=fid)
except ValueError as e:
    if "client is not initialized" in str(e):
        raise SystemExit("pass api_key= or export OPENAI_API_KEY") from e
    raise

Prevention

When it happens

Trigger: Calling litellm.create_fine_tuning_job() (OpenAI provider) with no api_key parameter, no client= argument, litellm.api_key unset, and OPENAI_API_KEY absent from the environment. get_openai_client returns None and the guard fires before any API request is made.

Common situations: Scripts migrated between machines where the env var was never exported; scheduled jobs/containers without the secret mounted; assuming the key set for chat completions (e.g. via a router config) is globally visible to the fine-tuning module; passing client=None explicitly along with no key.

Understand the failure class

Background: "API key is required" / "API key not found" / "No API key was set": the missing-api-key error family across 16 libraries — this error's family across 16 libraries.

Related errors


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/a57de6cddaa6cc39. Report an issue: GitHub.

Appendix: source

Thrown at litellm/llms/openai/fine_tuning/handler.py:126

        api_base: str | None,
        api_version: str | None,
        timeout: float | httpx.Timeout,
        max_retries: int | None,
        organization: str | None,
        client: OpenAI | AsyncOpenAI | AzureOpenAI | AsyncAzureOpenAI | None = None,
    ) -> LiteLLMFineTuningJob | Coroutine[Any, Any, LiteLLMFineTuningJob]:
        openai_client: Final[OpenAI | AsyncOpenAI | AzureOpenAI | AsyncAzureOpenAI | None] = self.get_openai_client(
            api_key=api_key,
            api_base=api_base,
            timeout=timeout,
            max_retries=max_retries,
            organization=organization,
            client=client,
            _is_async=_is_async,
            api_version=api_version,
        )
        if openai_client is None:
            raise ValueError(
                "OpenAI client is not initialized. Make sure api_key is passed or OPENAI_API_KEY is set in the environment."
            )

        if _is_async is True:
            if not isinstance(openai_client, (AsyncOpenAI, AsyncAzureOpenAI)):
                raise ValueError(
                    "OpenAI client is not an instance of AsyncOpenAI. Make sure you passed an AsyncOpenAI client."
                )
            return self.acreate_fine_tuning_job(
                create_fine_tuning_job_data=create_fine_tuning_job_data,
                openai_client=openai_client,
            )
        verbose_logger.debug("creating fine tuning job, args= %s", create_fine_tuning_job_data)
        response: Final = cast(OpenAI, openai_client).fine_tuning.jobs.create(**create_fine_tuning_job_data)
        return _litellm_fine_tuning_job_from_response(response)

    async def acancel_fine_tuning_job(
        self,

View on GitHub (pinned to 77b7c6c40c)