{"record":{"id":"f26d5e8dab027869","repo":"run-llama/llama_index","slug":"could-not-load-openai-model-if-you-intend","errorCode":null,"errorMessage":"\n******\nCould not load OpenAI model. If you intended to use OpenAI, please check your OPENAI_API_KEY.\nOriginal error:\n{e}\n******","messagePattern":"\n\\*\\*\\*\\*\\*\\*\nCould not load OpenAI model\\. If you intended to use OpenAI, please check your OPENAI_API_KEY\\.\nOriginal error:\n(.+?)\n\\*\\*\\*\\*\\*\\*","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"llama-index-core/llama_index/core/llms/utils.py","lineNumber":64,"sourceCode":"            llm.callback_manager = callback_manager or Settings.callback_manager\n            return llm\n\n        # return default OpenAI model. If it fails, return LlamaCPP\n        try:\n            from llama_index.llms.openai import OpenAI  # pants: no-infer-dep\n            from llama_index.llms.openai.utils import (\n                validate_openai_api_key,\n            )  # pants: no-infer-dep\n\n            llm = OpenAI()\n            validate_openai_api_key(llm.api_key)  # type: ignore\n        except ImportError:\n            raise ImportError(\n                \"`llama-index-llms-openai` package not found, \"\n                \"please run `pip install llama-index-llms-openai`\"\n            )\n        except ValueError as e:\n            raise ValueError(\n                \"\\n******\\n\"\n                \"Could not load OpenAI model. \"\n                \"If you intended to use OpenAI, please check your OPENAI_API_KEY.\\n\"\n                \"Original error:\\n\"\n                f\"{e!s}\"\n                \"\\n******\"\n            )\n\n    if isinstance(llm, str):\n        splits = llm.split(\":\", 1)\n        is_local = splits[0]\n        model_path = splits[1] if len(splits) > 1 else None\n        if is_local != \"local\":\n            raise ValueError(\n                \"llm must start with str 'local' or of type LLM or BaseLanguageModel\"\n            )\n        try:\n            from llama_index.llms.llama_cpp.llama_utils import (","sourceCodeStart":46,"sourceCodeEnd":82,"githubUrl":"https://github.com/run-llama/llama_index/blob/afd0fef371831f9bda13e5af7167cf4e981278ab/llama-index-core/llama_index/core/llms/utils.py#L46-L82","documentation":"During default-LLM resolution, llama-index constructs OpenAI() and calls validate_openai_api_key; if that raises (missing/invalid OPENAI_API_KEY), the ValueError is re-raised wrapped in a prominent message telling you to check the key. It exists so a missing key surfaces immediately at setup rather than as an opaque 401 later.","triggerScenarios":"Any implicit default-LLM resolution (no llm passed) in a process where OPENAI_API_KEY is unset, empty, malformed, or revoked, or where the key belongs to an incompatible endpoint/base_url.","commonSituations":"Env var not exported in the shell/venv/Docker/compose/cron; .env file not loaded; key rotated or revoked; CI secrets not wired; OPENAI_API_BASE_URL mismatched with the key type.","solutions":["Set a valid key: export OPENAI_API_KEY=sk-... (or wire it via your env/secret manager) and confirm with print(os.environ.get('OPENAI_API_KEY')).","If the key is fine but you don't want OpenAI, pass an explicit LLM: Settings.llm = <installed LLM>().","Verify the key with a minimal OpenAI API call or validate_openai_api_key to separate key issues from code issues.","Check that a custom base_url/proxy in the environment accepts this key."],"exampleFix":"# before\n# OPENAI_API_KEY unset -> ValueError on first index/query call\n# after\nimport os\nos.environ[\"OPENAI_API_KEY\"] = \"sk-...\"  # or export in shell\n# or bypass the default entirely\nfrom llama_index.core.llms.mock import MockLLM\nSettings.llm = MockLLM()","handlingStrategy":"validation","validationCode":"import os\n\ndef openai_key_present() -> bool:\n    return bool(os.environ.get(\"OPENAI_API_KEY\", \"\").strip())\n\nassert openai_key_present(), \"OPENAI_API_KEY must be set before creating indexes\"","typeGuard":null,"tryCatchPattern":"try:\n    Settings.llm = OpenAI()\nexcept ValueError as e:\n    if \"OPENAI_API_KEY\" in str(e):\n        raise SystemExit(\"Set OPENAI_API_KEY in the environment\") from e\n    raise","preventionTips":["Load .env files explicitly (python-dotenv) at process start.","Set an explicit Settings.llm in offline/test environments (e.g. MockLLM).","Validate the key's presence in a startup health check, not on first query."],"tags":["llama-index","openai","api-key","configuration","environment"],"backgroundTag":null,"analyzedSha":"afd0fef371831f9bda13e5af7167cf4e981278ab","analyzedAt":"2026-08-15T05:42:58.429Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}