{"record":{"id":"c252d45c82f53325","repo":"binary-husky/gpt_academic","slug":"gemini-api-key","errorCode":null,"errorMessage":"请配置 GEMINI_API_KEY。","messagePattern":"请配置 GEMINI_API_KEY。","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"critical","filePath":"request_llms/bridge_google_gemini.py","lineNumber":22,"sourceCode":"# @Descr   :\nimport json\nimport re\nimport os\nimport time\nfrom request_llms.com_google import GoogleChatInit\nfrom toolbox import ChatBotWithCookies\nfrom toolbox import get_conf, update_ui, update_ui_latest_msg, have_any_recent_upload_image_files, trimmed_format_exc, log_chat, encode_image\n\nproxies, TIMEOUT_SECONDS, MAX_RETRY = get_conf('proxies', 'TIMEOUT_SECONDS', 'MAX_RETRY')\ntimeout_bot_msg = '[Local Message] Request timeout. Network error. Please check proxy settings in config.py.' + \\\n                  '网络错误，检查代理服务器是否可用，以及代理设置的格式是否正确，格式须是[协议]://[地址]:[端口]，缺一不可。'\n\n\ndef predict_no_ui_long_connection(inputs:str, llm_kwargs:dict, history:list=[], sys_prompt:str=\"\", observe_window:list=[],\n                                  console_silence:bool=False):\n    # 检查API_KEY\n    if get_conf(\"GEMINI_API_KEY\") == \"\":\n        raise ValueError(f\"请配置 GEMINI_API_KEY。\")\n\n    genai = GoogleChatInit(llm_kwargs)\n    watch_dog_patience = 5  # 看门狗的耐心, 设置5秒即可\n    gpt_replying_buffer = ''\n    stream_response = genai.generate_chat(inputs, llm_kwargs, history, sys_prompt)\n    for response in stream_response:\n        results = response.decode()\n        match = re.search(r'\"text\":\\s*\"((?:[^\"\\\\]|\\\\.)*)\"', results, flags=re.DOTALL)\n        error_match = re.search(r'\\\"message\\\":\\s*\\\"(.*?)\\\"', results, flags=re.DOTALL)\n        if match:\n            try:\n                paraphrase = json.loads('{\"text\": \"%s\"}' % match.group(1))\n            except:\n                raise ValueError(f\"解析GEMINI消息出错。\")\n            buffer = paraphrase['text']\n            gpt_replying_buffer += buffer\n            if len(observe_window) >= 1:\n                observe_window[0] = gpt_replying_buffer","sourceCodeStart":4,"sourceCodeEnd":40,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/request_llms/bridge_google_gemini.py#L4-L40","documentation":"ValueError raised at the top of Gemini predict_no_ui_long_connection when get_conf(\"GEMINI_API_KEY\") returns \"\" — the key was never set in config.py/config_private.py. The Gemini path builds signed Google AI (GenerativeLanguage) requests from this key, so the bridge aborts before constructing GoogleChatInit-dependent work. Configuration is the only fix; there is no in-chat fallback like the OpenAI bridges.","triggerScenarios":"Selecting a Gemini model while GEMINI_API_KEY is empty in config; config_private.py exists but omits GEMINI_API_KEY; key stored only in an env var the config loader doesn't read.","commonSituations":"Fresh installs trying google gemini models; users who configured OpenAI/Anthropic keys and assumed Gemini shares them; Google AI Studio key never generated.","solutions":["Create a key at aistudio.google.com/app/apikey and set GEMINI_API_KEY = \"AIza...\" in config_private.py, then restart.","Confirm config_private.py is in the project root so it overrides config.py.","Verify the key works with a direct curl to the GenerativeLanguage API to rule out revocation/quota.","If behind restricted networks, also configure proxies — the follow-up request needs reachability of generativelanguage.googleapis.com."],"exampleFix":"# config_private.py\nGEMINI_API_KEY = \"AIzaSy-your-real-key\"","handlingStrategy":"validation","validationCode":"from toolbox import get_conf\nassert get_conf('GEMINI_API_KEY') != '', \"set GEMINI_API_KEY in config_private.py (create at aistudio.google.com/app/apikey)\"","typeGuard":null,"tryCatchPattern":"try:\n    result = predict_no_ui_long_connection(inputs, llm_kwargs, history, sys_prompt, observe_window)\nexcept ValueError as e:\n    if 'GEMINI_API_KEY' in str(e):\n        disable_gemini_models_until_configured()\n    else:\n        raise","preventionTips":["Add GEMINI_API_KEY to the install-time config checklist.","Validate at startup and hide Gemini models when the key is empty.","Test the key with a direct GenerativeLanguage curl before first use.","Ensure generativelanguage.googleapis.com is reachable through your proxy."],"tags":["gemini","google","api-key","configuration","authentication"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}