666ghj/MiroFish · error · ValueError

LLM_API_KEY 未配置

Error message

LLM_API_KEY 未配置

What it means

ValueError raised in LLMClient.__init__ when neither the constructor argument api_key nor Config.LLM_API_KEY is set. The client wraps the OpenAI SDK, which requires an API key, so construction fails immediately rather than on the first request.

Source

Thrown at backend/app/utils/llm_client.py:105

            return True
    return False


class LLMClient:
    """LLM客户端"""
    
    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
        model: Optional[str] = None
    ):
        self.api_key = api_key or Config.LLM_API_KEY
        self.base_url = base_url or Config.LLM_BASE_URL
        self.model = model or Config.LLM_MODEL_NAME
        
        if not self.api_key:
            raise ValueError("LLM_API_KEY 未配置")
        
        self.client = OpenAI(
            api_key=self.api_key,
            base_url=self.base_url
        )

    def _create_completion(
        self,
        *,
        messages: List[Dict[str, str]],
        temperature: Optional[float],
        max_tokens: Optional[int],
        response_format: Optional[Dict[str, Any]],
    ) -> Any:
        """Send one raw Chat Completions request through the compatibility layer."""

        return create_chat_completion(
            self.client,

View on GitHub (pinned to b5b53acc57)

Solutions

  1. Set LLM_API_KEY (and check LLM_BASE_URL/LLM_MODEL_NAME while at it) in the environment/config before creating LLMClient
  2. Pass api_key explicitly when the key comes from a secret manager
  3. Validate required config once at application startup and abort with a clear message listing all missing keys

Example fix

# before
client = LLMClient()  # LLM_API_KEY unset -> ValueError

# after
api_key = os.environ.get("LLM_API_KEY")
if not api_key:
    raise SystemExit("LLM_API_KEY is required")
client = LLMClient(api_key=api_key)
Defensive patterns

Strategy: validation

Validate before calling

if not (api_key or Config.LLM_API_KEY):
    raise SystemExit("LLM_API_KEY is required")

Try / catch

try:
    client = LLMClient(api_key=key)
except ValueError as e:
    logger.error("config error: %s", e)
    raise

Prevention

When it happens

Trigger: Instantiating LLMClient() in an environment where LLM_API_KEY is unset/empty — missing .env, env var not passed into the container, or config loaded too late.

Common situations: Deployments without secrets injected, CI pipelines, local runs after cloning without copying .env.example, or a renamed config key.

Related errors


AI-assisted analysis of 666ghj/MiroFish@b5b53acc57 (2026-08-14). Data as JSON: /api/errors/d37e89e4f5f846e0. Report an issue: GitHub.