hsliuping/TradingAgents-CN · critical · ValueError

使用OpenRouter需要设置OPENROUTER_API_KEY或OPENAI_API_KEY环境变量

Error message

使用OpenRouter需要设置OPENROUTER_API_KEY或OPENAI_API_KEY环境变量

What it means

TradingAgentsGraph.__init__ raises this when provider is 'openrouter' and neither OPENROUTER_API_KEY nor OPENAI_API_KEY is set. OpenRouter keys are OpenAI-compatible, hence the OpenAI fallback. The check is purely environmental — DB-configured keys are not consulted in this branch.

Source

Thrown at tradingagents/graph/trading_graph.py:299

                **_deep_extra,
            )

            logger.info(f"✅ [混合模式] LLM 实例创建成功")

        elif normalized_provider in {"openai", "siliconflow", "openrouter", "aihubmix", "volcengine", "ollama"}:
            provider = normalized_provider
            logger.info(f"🔧 [{provider}-快速模型] max_tokens={quick_max_tokens}, temperature={quick_temperature}, timeout={quick_timeout}s")
            logger.info(f"🔧 [{provider}-深度模型] max_tokens={deep_max_tokens}, temperature={deep_temperature}, timeout={deep_timeout}s")

            api_key = None
            if provider == "siliconflow":
                api_key = os.getenv('SILICONFLOW_API_KEY')
                if not api_key:
                    raise ValueError("使用SiliconFlow需要设置SILICONFLOW_API_KEY环境变量")
            elif provider == "openrouter":
                api_key = os.getenv('OPENROUTER_API_KEY') or os.getenv('OPENAI_API_KEY')
                if not api_key:
                    raise ValueError("使用OpenRouter需要设置OPENROUTER_API_KEY或OPENAI_API_KEY环境变量")
            elif provider == "aihubmix":
                api_key = os.getenv('AIHUBMIX_API_KEY')
                if not api_key:
                    raise ValueError("使用AiHubMix需要设置AIHUBMIX_API_KEY环境变量")
            elif provider == "volcengine":
                api_key = os.getenv('VOLCENGINE_API_KEY') or os.getenv('ARK_API_KEY')
                if not api_key:
                    raise ValueError("使用火山方舟需要设置VOLCENGINE_API_KEY或ARK_API_KEY环境变量")
            elif provider == "volcengine_coding":
                api_key = os.getenv('VOLCENGINE_CODING_API_KEY')
                if not api_key:
                    raise ValueError("使用火山方舟编程需要设置VOLCENGINE_CODING_API_KEY环境变量")

            self.deep_thinking_llm, self.quick_thinking_llm = _create_provider_pair(
                provider=provider,
                config=self.config,
                quick_temperature=quick_temperature,
                quick_max_tokens=quick_max_tokens,

View on GitHub (pinned to 74783e8817)

Solutions

  1. export OPENROUTER_API_KEY=sk-or-... (preferred) or OPENAI_API_KEY=sk-... as fallback
  2. Add the variable to .env / docker-compose environment and ensure load_dotenv() runs before constructing TradingAgentsGraph
  3. Confirm the variable name spelling — OPENROUTER_API_KEY, not OPENROUTER_KEY

Example fix

# before
graph = TradingAgentsGraph(config={"llm_provider": "openrouter"})

# after
# shell: export OPENROUTER_API_KEY=sk-or-...
graph = TradingAgentsGraph(config={"llm_provider": "openrouter"})
Defensive patterns

Strategy: validation

Validate before calling

import os
if provider == "openrouter" and not (os.getenv("OPENROUTER_API_KEY") or os.getenv("OPENAI_API_KEY")):
    raise SystemExit("Set OPENROUTER_API_KEY (or OPENAI_API_KEY) before starting")

Type guard

def has_openrouter_key() -> bool:
    return bool(os.getenv("OPENROUTER_API_KEY") or os.getenv("OPENAI_API_KEY"))

Try / catch

try:
    graph = TradingAgentsGraph(config=cfg)
except ValueError as e:
    if "OpenRouter" in str(e):
        log.error("Provision OPENROUTER_API_KEY in the service environment")
        raise SystemExit(2) from e
    raise

Prevention

When it happens

Trigger: Constructing the graph with llm_provider="openrouter" while both OPENROUTER_API_KEY and OPENAI_API_KEY are absent from the environment.

Common situations: Env var not passed into docker container or background service; user assumed OpenAI key in .env would be picked up but .env isn't loaded; CI runs without secrets configured.

Understand the failure class

Background: "API key is required" / "API key not found" / "No API key was set": the missing-api-key error family across 16 libraries — this error's family across 16 libraries.

Related errors


AI-assisted analysis of hsliuping/TradingAgents-CN@74783e8817 (2026-08-28). Data as JSON: /api/errors/eb42eb8c06e4e950. Report an issue: GitHub.