hsliuping/TradingAgents-CN · critical · ValueError

使用Google AI需要在数据库中配置API Key或设置GOOGLE_API_KEY环境变量

Error message

使用Google AI需要在数据库中配置API Key或设置GOOGLE_API_KEY环境变量

What it means

TradingAgentsGraph.__init__ raises this in the Google AI branch when no key resolves from config (quick_api_key or deep_api_key) nor the GOOGLE_API_KEY environment variable. Unlike the standalone create_llm_by_provider path, this branch first checks database/web-UI config keys. Thrown at construction before clients are built.

Source

Thrown at tradingagents/graph/trading_graph.py:354

                temperature=deep_temperature,
                max_tokens=deep_max_tokens,
                timeout=deep_timeout
            )
            self.quick_thinking_llm = ChatAnthropic(
                model=self.config["quick_think_llm"],
                base_url=self.config["backend_url"],
                temperature=quick_temperature,
                max_tokens=quick_max_tokens,
                timeout=quick_timeout
            )
        elif normalized_provider == "google":
            # 使用统一 llm_clients 入口,但底层仍返回 ChatGoogleOpenAI 兼容适配器
            logger.info("🔧 使用统一 llm_clients 路径初始化 Google AI(保留工具调用兼容行为)")

            # 🔥 优先使用数据库配置的 API Key,否则从环境变量读取
            google_api_key = self.config.get("quick_api_key") or self.config.get("deep_api_key") or os.getenv('GOOGLE_API_KEY')
            if not google_api_key:
                raise ValueError("使用Google AI需要在数据库中配置API Key或设置GOOGLE_API_KEY环境变量")

            logger.info(f"🔑 [Google AI] API Key 来源: {'数据库配置' if self.config.get('quick_api_key') or self.config.get('deep_api_key') else '环境变量'}")

            logger.info(f"🔧 [Google-快速模型] max_tokens={quick_max_tokens}, temperature={quick_temperature}, timeout={quick_timeout}s")
            logger.info(f"🔧 [Google-深度模型] max_tokens={deep_max_tokens}, temperature={deep_temperature}, timeout={deep_timeout}s")

            # 获取 backend_url(如果配置中有的话)
            backend_url = self.config.get("backend_url")
            if backend_url:
                logger.info(f"🔧 [Google AI] 使用配置的 backend_url: {backend_url}")
            else:
                logger.info(f"🔧 [Google AI] 未配置 backend_url,使用默认端点")

            # 合并 Google 特殊的 transport 参数和 reasoning_effort
            _google_quick_extra = {"transport": "rest"}
            if _quick_extra:
                _google_quick_extra.update(_quick_extra)

View on GitHub (pinned to 74783e8817)

Solutions

  1. Set GOOGLE_API_KEY in the environment, or put the key into config as quick_api_key/deep_api_key (Settings -> LLM Providers in the web UI)
  2. If using dotenv, verify load_dotenv() executes before TradingAgentsGraph is instantiated
  3. Check that the selected provider profile in the UI is actually 'google' and its key fields are populated

Example fix

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

# after
cfg = {"llm_provider": "google", "quick_api_key": "AIza...", "deep_api_key": "AIza..."}
graph = TradingAgentsGraph(config=cfg)
Defensive patterns

Strategy: validation

Validate before calling

cfg_key = cfg.get("quick_api_key") or cfg.get("deep_api_key") or os.getenv("GOOGLE_API_KEY")
if provider == "google" and not cfg_key:
    raise SystemExit("Set quick_api_key/deep_api_key in config or GOOGLE_API_KEY env")

Type guard

def has_google_credential(cfg: dict) -> bool:
    return bool(cfg.get("quick_api_key") or cfg.get("deep_api_key") or os.getenv("GOOGLE_API_KEY"))

Try / catch

try:
    graph = TradingAgentsGraph(config=cfg)
except ValueError as e:
    if "Google AI" in str(e):
        raise SystemExit("Configure Google key via web UI or GOOGLE_API_KEY") from e
    raise

Prevention

When it happens

Trigger: Constructing TradingAgentsGraph with provider "google" while config lacks quick_api_key/deep_api_key and GOOGLE_API_KEY is unset in the environment.

Common situations: Saved the key in the web UI under a different provider profile so config lookups miss; .env missing in the deployment running the graph; migrating configs between machines without secrets.

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