{"record":{"id":"a57de6cddaa6cc39","repo":"BerriAI/litellm","slug":"openai-client-is-not-initialized-make-sure-api-ke-a57de6","errorCode":null,"errorMessage":"OpenAI client is not initialized. Make sure api_key is passed or OPENAI_API_KEY is set in the environment.","messagePattern":"OpenAI client is not initialized\\. Make sure api_key is passed or OPENAI_API_KEY is set in the environment\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"litellm/llms/openai/fine_tuning/handler.py","lineNumber":126,"sourceCode":"        api_base: str | None,\n        api_version: str | None,\n        timeout: float | httpx.Timeout,\n        max_retries: int | None,\n        organization: str | None,\n        client: OpenAI | AsyncOpenAI | AzureOpenAI | AsyncAzureOpenAI | None = None,\n    ) -> LiteLLMFineTuningJob | Coroutine[Any, Any, LiteLLMFineTuningJob]:\n        openai_client: Final[OpenAI | AsyncOpenAI | AzureOpenAI | AsyncAzureOpenAI | None] = self.get_openai_client(\n            api_key=api_key,\n            api_base=api_base,\n            timeout=timeout,\n            max_retries=max_retries,\n            organization=organization,\n            client=client,\n            _is_async=_is_async,\n            api_version=api_version,\n        )\n        if openai_client is None:\n            raise ValueError(\n                \"OpenAI client is not initialized. Make sure api_key is passed or OPENAI_API_KEY is set in the environment.\"\n            )\n\n        if _is_async is True:\n            if not isinstance(openai_client, (AsyncOpenAI, AsyncAzureOpenAI)):\n                raise ValueError(\n                    \"OpenAI client is not an instance of AsyncOpenAI. Make sure you passed an AsyncOpenAI client.\"\n                )\n            return self.acreate_fine_tuning_job(\n                create_fine_tuning_job_data=create_fine_tuning_job_data,\n                openai_client=openai_client,\n            )\n        verbose_logger.debug(\"creating fine tuning job, args= %s\", create_fine_tuning_job_data)\n        response: Final = cast(OpenAI, openai_client).fine_tuning.jobs.create(**create_fine_tuning_job_data)\n        return _litellm_fine_tuning_job_from_response(response)\n\n    async def acancel_fine_tuning_job(\n        self,","sourceCodeStart":108,"sourceCodeEnd":144,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/llms/openai/fine_tuning/handler.py#L108-L144","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Pass api_key explicitly to create_fine_tuning_job, or pass a pre-built openai.OpenAI client via client=","Export OPENAI_API_KEY in the runtime environment (shell profile, .env loaded before import, CI secret, docker -e)","Set litellm.api_key = 'sk-...' once at startup if you use module-level config","If you intentionally pass client=, make sure it is an instantiated OpenAI()/AzureOpenAI() object, not None"],"exampleFix":"# before\njob = litellm.create_fine_tuning_job(model=\"gpt-4o-2024-08-06\", training_file=file_id)\n# ValueError: OpenAI client is not initialized...\n\n# after\njob = litellm.create_fine_tuning_job(\n    model=\"gpt-4o-2024-08-06\",\n    training_file=file_id,\n    api_key=os.environ[\"OPENAI_API_KEY\"],\n)","handlingStrategy":"validation","validationCode":"import os\n\napi_key = os.getenv(\"OPENAI_API_KEY\")\nif not api_key:\n    raise SystemExit(\"OPENAI_API_KEY not set - cannot create fine-tuning jobs\")\n\njob = litellm.create_fine_tuning_job(\n    model=\"gpt-4o-2024-08-06\", training_file=file_id, api_key=api_key\n)","typeGuard":"def can_run_finetuning(api_key, client) -> bool:\n    \"\"\"True when a fine-tuning call has credentials or a ready client.\"\"\"\n    import os\n    return bool(api_key or client is not None or os.getenv(\"OPENAI_API_KEY\"))","tryCatchPattern":"try:\n    job = litellm.create_fine_tuning_job(model=m, training_file=fid)\nexcept ValueError as e:\n    if \"client is not initialized\" in str(e):\n        raise SystemExit(\"pass api_key= or export OPENAI_API_KEY\") from e\n    raise","preventionTips":["Pass api_key explicitly on every fine-tuning call rather than relying on environment state","Verify required env vars in a startup checklist before long fine-tuning pipelines begin","If injecting clients, inject constructed OpenAI()/AsyncOpenAI() instances, never None","Centralize key loading (dotenv/secret manager) in one module imported first at process start"],"tags":["fine-tuning","missing-api-key","client-init","openai","env-var"],"backgroundTag":"missing-api-key","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}