hsliuping/TradingAgents-CN · critical · ValueError

使用自定义OpenAI端点需要设置CUSTOM_OPENAI_API_KEY环境变量

Error message

使用自定义OpenAI端点需要设置CUSTOM_OPENAI_API_KEY环境变量

What it means

TradingAgentsGraph.__init__ raises this for provider 'custom_openai' when the CUSTOM_OPENAI_API_KEY environment variable is unset. Note this branch reads only the environment — the key cannot come from DB config — while the base URL does come from config (custom_openai_base_url, defaulting to OpenAI's endpoint).

Source

Thrown at tradingagents/graph/trading_graph.py:429

            self.deep_thinking_llm, self.quick_thinking_llm = _create_provider_pair(
                provider="deepseek",
                config=self.config,
                quick_temperature=quick_temperature,
                quick_max_tokens=quick_max_tokens,
                quick_timeout=quick_timeout,
                deep_temperature=deep_temperature,
                deep_max_tokens=deep_max_tokens,
                deep_timeout=deep_timeout,
                backend_url=deepseek_base_url,
                api_key=deepseek_api_key,
                quick_extra_kwargs=_quick_extra if _quick_extra else None,
                deep_extra_kwargs=_deep_extra if _deep_extra else None,
            )
            logger.info("✅ [DeepSeek] 已通过 llm_clients 初始化成功并应用用户配置的模型参数")
        elif normalized_provider == "custom_openai":
            custom_api_key = os.getenv('CUSTOM_OPENAI_API_KEY')
            if not custom_api_key:
                raise ValueError("使用自定义OpenAI端点需要设置CUSTOM_OPENAI_API_KEY环境变量")

            custom_base_url = self.config.get("custom_openai_base_url", "https://api.openai.com/v1")
            logger.info(f"🔧 [自定义OpenAI] 使用端点: {custom_base_url}")
            self.deep_thinking_llm, self.quick_thinking_llm = _create_provider_pair(
                provider="custom_openai",
                config=self.config,
                quick_temperature=quick_temperature,
                quick_max_tokens=quick_max_tokens,
                quick_timeout=quick_timeout,
                deep_temperature=deep_temperature,
                deep_max_tokens=deep_max_tokens,
                deep_timeout=deep_timeout,
                backend_url=custom_base_url,
                api_key=custom_api_key,
                quick_extra_kwargs=_quick_extra if _quick_extra else None,
                deep_extra_kwargs=_deep_extra if _deep_extra else None,
            )
            logger.info("✅ [自定义OpenAI] 已通过 llm_clients 初始化成功并应用用户配置的模型参数")

View on GitHub (pinned to 74783e8817)

Solutions

  1. export CUSTOM_OPENAI_API_KEY=<token-or-dummy> (some local servers accept any non-empty value)
  2. Also set custom_openai_base_url in config to your endpoint if it differs from https://api.openai.com/v1
  3. Persist the variable in .env/compose and load dotenv before graph init

Example fix

# before
graph = TradingAgentsGraph(config={"llm_provider": "custom_openai", "custom_openai_base_url": "http://localhost:8000/v1"})

# after
# export CUSTOM_OPENAI_API_KEY=local-token
cfg = {"llm_provider": "custom_openai", "custom_openai_base_url": "http://localhost:8000/v1"}
graph = TradingAgentsGraph(config=cfg)
Defensive patterns

Strategy: validation

Validate before calling

import os
if provider == "custom_openai" and not os.getenv("CUSTOM_OPENAI_API_KEY"):
    raise SystemExit("Set CUSTOM_OPENAI_API_KEY (required even for local endpoints)")

Type guard

def has_custom_openai_key() -> bool:
    return bool(os.getenv("CUSTOM_OPENAI_API_KEY"))

Try / catch

try:
    graph = TradingAgentsGraph(config=cfg)
except ValueError as e:
    if "CUSTOM_OPENAI_API_KEY" in str(e):
        os.environ["CUSTOM_OPENAI_API_KEY"] = "dummy"  # only for auth-free local endpoints
        graph = TradingAgentsGraph(config=cfg)
    else:
        raise

Prevention

When it happens

Trigger: llm_provider="custom_openai" without CUSTOM_OPENAI_API_KEY exported, e.g. pointing at a self-hosted vLLM/LiteLLM endpoint that still requires auth.

Common situations: Using an OpenAI-compatible gateway (one-api, LiteLLM proxy) and forgetting its token; local vLLM with no auth where users expect to skip the key but the branch requires it; env var missing in service unit.

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/351dd208c10c0a70. Report an issue: GitHub.