{"record":{"id":"c76f122470723dee","repo":"hsliuping/TradingAgents-CN","slug":"google-ai-api-key-google-api-key","errorCode":null,"errorMessage":"使用Google AI需要在数据库中配置API Key或设置GOOGLE_API_KEY环境变量","messagePattern":"使用Google AI需要在数据库中配置API Key或设置GOOGLE_API_KEY环境变量","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"critical","filePath":"tradingagents/graph/trading_graph.py","lineNumber":354,"sourceCode":"                temperature=deep_temperature,\n                max_tokens=deep_max_tokens,\n                timeout=deep_timeout\n            )\n            self.quick_thinking_llm = ChatAnthropic(\n                model=self.config[\"quick_think_llm\"],\n                base_url=self.config[\"backend_url\"],\n                temperature=quick_temperature,\n                max_tokens=quick_max_tokens,\n                timeout=quick_timeout\n            )\n        elif normalized_provider == \"google\":\n            # 使用统一 llm_clients 入口，但底层仍返回 ChatGoogleOpenAI 兼容适配器\n            logger.info(\"🔧 使用统一 llm_clients 路径初始化 Google AI（保留工具调用兼容行为）\")\n\n            # 🔥 优先使用数据库配置的 API Key，否则从环境变量读取\n            google_api_key = self.config.get(\"quick_api_key\") or self.config.get(\"deep_api_key\") or os.getenv('GOOGLE_API_KEY')\n            if not google_api_key:\n                raise ValueError(\"使用Google AI需要在数据库中配置API Key或设置GOOGLE_API_KEY环境变量\")\n\n            logger.info(f\"🔑 [Google AI] API Key 来源: {'数据库配置' if self.config.get('quick_api_key') or self.config.get('deep_api_key') else '环境变量'}\")\n\n            logger.info(f\"🔧 [Google-快速模型] max_tokens={quick_max_tokens}, temperature={quick_temperature}, timeout={quick_timeout}s\")\n            logger.info(f\"🔧 [Google-深度模型] max_tokens={deep_max_tokens}, temperature={deep_temperature}, timeout={deep_timeout}s\")\n\n            # 获取 backend_url（如果配置中有的话）\n            backend_url = self.config.get(\"backend_url\")\n            if backend_url:\n                logger.info(f\"🔧 [Google AI] 使用配置的 backend_url: {backend_url}\")\n            else:\n                logger.info(f\"🔧 [Google AI] 未配置 backend_url，使用默认端点\")\n\n            # 合并 Google 特殊的 transport 参数和 reasoning_effort\n            _google_quick_extra = {\"transport\": \"rest\"}\n            if _quick_extra:\n                _google_quick_extra.update(_quick_extra)\n","sourceCodeStart":336,"sourceCodeEnd":372,"githubUrl":"https://github.com/hsliuping/TradingAgents-CN/blob/74783e8817d6cf6de29867880631cc555153f36b/tradingagents/graph/trading_graph.py#L336-L372","documentation":"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.","triggerScenarios":"Constructing TradingAgentsGraph with provider \"google\" while config lacks quick_api_key/deep_api_key and GOOGLE_API_KEY is unset in the environment.","commonSituations":"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.","solutions":["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)","If using dotenv, verify load_dotenv() executes before TradingAgentsGraph is instantiated","Check that the selected provider profile in the UI is actually 'google' and its key fields are populated"],"exampleFix":"# before\ngraph = TradingAgentsGraph(config={\"llm_provider\": \"google\"})\n\n# after\ncfg = {\"llm_provider\": \"google\", \"quick_api_key\": \"AIza...\", \"deep_api_key\": \"AIza...\"}\ngraph = TradingAgentsGraph(config=cfg)","handlingStrategy":"validation","validationCode":"cfg_key = cfg.get(\"quick_api_key\") or cfg.get(\"deep_api_key\") or os.getenv(\"GOOGLE_API_KEY\")\nif provider == \"google\" and not cfg_key:\n    raise SystemExit(\"Set quick_api_key/deep_api_key in config or GOOGLE_API_KEY env\")","typeGuard":"def has_google_credential(cfg: dict) -> bool:\n    return bool(cfg.get(\"quick_api_key\") or cfg.get(\"deep_api_key\") or os.getenv(\"GOOGLE_API_KEY\"))","tryCatchPattern":"try:\n    graph = TradingAgentsGraph(config=cfg)\nexcept ValueError as e:\n    if \"Google AI\" in str(e):\n        raise SystemExit(\"Configure Google key via web UI or GOOGLE_API_KEY\") from e\n    raise","preventionTips":["Persist keys in the web UI DB so config-based lookup wins over env","Load dotenv before graph init in scripts","Keep provider profile and its key fields in sync in the UI"],"tags":["api-key","missing-env-var","google","configuration","llm"],"backgroundTag":"missing-api-key","analyzedSha":"74783e8817d6cf6de29867880631cc555153f36b","analyzedAt":"2026-08-28T11:39:07.729Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}