{"record":{"id":"5109fbe730ece93a","repo":"datawhalechina/hello-agents","slug":"llm-api-key-5109fb","errorCode":null,"errorMessage":"请设置 LLM_API_KEY 环境变量","messagePattern":"请设置 LLM_API_KEY 环境变量","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"Co-creation-projects/megg-ops-roleplay_agent/roleplay_agent.py","lineNumber":17,"sourceCode":"import os\nfrom openai import OpenAI\nfrom dotenv import load_dotenv\nimport time\n\n# 加载环境变量\nload_dotenv()\n\nclass CharacterRoleplayAgent:\n    def __init__(self):\n        # 从环境变量获取配置\n        api_key = os.getenv(\"LLM_API_KEY\")\n        model_id = os.getenv(\"LLM_MODEL_ID\", \"default-model\")\n        base_url = os.getenv(\"LLM_BASE_URL\", None)\n        \n        if not api_key:\n            raise ValueError(\"请设置 LLM_API_KEY 环境变量\")\n        \n        # 配置 OpenAI 客户端\n        client_params = {\n            \"api_key\": api_key,\n            \"model\": model_id\n        }\n        \n        if base_url:\n            client_params[\"base_url\"] = base_url\n        \n        self.client = OpenAI(**{k: v for k, v in client_params.items() if k != 'model'})\n        self.model_id = model_id\n        self.chat = None\n        self.character_config = None\n\n    def setup_character(self, name, source_material, personality, opening_line=None):\n        \"\"\"\n        设置角色配置并初始化聊天","sourceCodeStart":1,"sourceCodeEnd":35,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/megg-ops-roleplay_agent/roleplay_agent.py#L1-L35","documentation":"CharacterRoleplayAgent.__init__ reads LLM_API_KEY via os.getenv and raises ValueError when it is empty. load_dotenv() runs at import time, so the .env file must exist in the process's working directory (or be found by python-dotenv's search) before this class is instantiated. Any launch path that bypasses both .env and the shell environment (no LLM_API_KEY exported) hits this guard immediately.","triggerScenarios":"python roleplay_agent.py from a directory without .env; .env present but the key line named differently (OPENAI_API_KEY, LLM_APIKEY) or commented out; running under an IDE/debugger whose cwd differs from the project dir so load_dotenv() finds nothing; deploying without copying .env.","commonSituations":"Fresh clone without creating .env from a template; CI or containerized run where the env var was never injected; IDE launch config overriding the working directory; quotes/spaces around the value in .env plus a strict provider rejecting it later (guard only checks non-empty here).","solutions":["Create .env next to roleplay_agent.py with LLM_API_KEY=sk-... (and optionally LLM_MODEL_ID, LLM_BASE_URL) and run the script from that directory.","Or export it in the launching shell: export LLM_API_KEY=... before python roleplay_agent.py.","Give load_dotenv() an explicit path — load_dotenv(Path(__file__).parent / \".env\") — so cwd no longer matters.","For services/containers, inject LLM_API_KEY as a real environment variable (secret ref) instead of relying on .env.","Add an early startup log of which env names were found (names only, never values) to speed up diagnosis."],"exampleFix":"# before\nload_dotenv()\n...\napi_key = os.getenv(\"LLM_API_KEY\")\n# after\nfrom pathlib import Path\nload_dotenv(Path(__file__).resolve().parent / \".env\")\napi_key = os.getenv(\"LLM_API_KEY\")","handlingStrategy":"validation","validationCode":"import os\nif not os.getenv(\"LLM_API_KEY\"):\n    raise SystemExit(\"LLM_API_KEY missing — create .env next to roleplay_agent.py or export it\")","typeGuard":null,"tryCatchPattern":"try:\n    agent = CharacterRoleplayAgent()\nexcept ValueError as e:\n    logger.error(\"roleplay agent config incomplete: %s\", e)  # config error — no retry\n    raise","preventionTips":["Call load_dotenv with an explicit absolute path so cwd does not matter","Ship .env.example with LLM_API_KEY/LLM_MODEL_ID/LLM_BASE_URL","Check env presence in a startup preflight, never in a request path"],"tags":["api-key","environment-variables","dotenv","configuration","python"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}