datawhalechina/hello-agents · error · ValueError

请设置 LLM_API_KEY 环境变量

Error message

请设置 LLM_API_KEY 环境变量

What it means

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.

Source

Thrown at Co-creation-projects/megg-ops-roleplay_agent/roleplay_agent.py:17

import os
from openai import OpenAI
from dotenv import load_dotenv
import time

# 加载环境变量
load_dotenv()

class CharacterRoleplayAgent:
    def __init__(self):
        # 从环境变量获取配置
        api_key = os.getenv("LLM_API_KEY")
        model_id = os.getenv("LLM_MODEL_ID", "default-model")
        base_url = os.getenv("LLM_BASE_URL", None)
        
        if not api_key:
            raise ValueError("请设置 LLM_API_KEY 环境变量")
        
        # 配置 OpenAI 客户端
        client_params = {
            "api_key": api_key,
            "model": model_id
        }
        
        if base_url:
            client_params["base_url"] = base_url
        
        self.client = OpenAI(**{k: v for k, v in client_params.items() if k != 'model'})
        self.model_id = model_id
        self.chat = None
        self.character_config = None

    def setup_character(self, name, source_material, personality, opening_line=None):
        """
        设置角色配置并初始化聊天

View on GitHub (pinned to 606a07d341)

Solutions

  1. 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.
  2. Or export it in the launching shell: export LLM_API_KEY=... before python roleplay_agent.py.
  3. Give load_dotenv() an explicit path — load_dotenv(Path(__file__).parent / ".env") — so cwd no longer matters.
  4. For services/containers, inject LLM_API_KEY as a real environment variable (secret ref) instead of relying on .env.
  5. Add an early startup log of which env names were found (names only, never values) to speed up diagnosis.

Example fix

# before
load_dotenv()
...
api_key = os.getenv("LLM_API_KEY")
# after
from pathlib import Path
load_dotenv(Path(__file__).resolve().parent / ".env")
api_key = os.getenv("LLM_API_KEY")
Defensive patterns

Strategy: validation

Validate before calling

import os
if not os.getenv("LLM_API_KEY"):
    raise SystemExit("LLM_API_KEY missing — create .env next to roleplay_agent.py or export it")

Try / catch

try:
    agent = CharacterRoleplayAgent()
except ValueError as e:
    logger.error("roleplay agent config incomplete: %s", e)  # config error — no retry
    raise

Prevention

When it happens

Trigger: 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.

Common situations: 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).

Related errors


AI-assisted analysis of datawhalechina/hello-agents@606a07d341 (2026-08-14). Data as JSON: /api/errors/5109fbe730ece93a. Report an issue: GitHub.