{"record":{"id":"d29ec091b016166d","repo":"binary-husky/gpt_academic","slug":"openai-error-msg-d29ec0","errorCode":null,"errorMessage":"OpenAI拒绝了请求：{error_msg}","messagePattern":"OpenAI拒绝了请求：(.+?)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"request_llms/bridge_openrouter.py","lineNumber":181,"sourceCode":"    stream_response = response.iter_lines()\n    result = ''\n    json_data = None\n    while True:\n        try: chunk = next(stream_response)\n        except StopIteration:\n            break\n        except requests.exceptions.ConnectionError:\n            chunk = next(stream_response) # 失败了，重试一次？再失败就没办法了。\n        chunk_decoded, chunkjson, has_choices, choice_valid, has_content, has_role = decode_chunk(chunk)\n        if len(chunk_decoded)==0 or chunk_decoded.startswith(':'): continue\n        if not chunk_decoded.startswith('data:'):\n            error_msg = get_full_error(chunk, stream_response).decode()\n            if \"reduce the length\" in error_msg:\n                raise ConnectionAbortedError(\"OpenAI拒绝了请求:\" + error_msg)\n            elif \"\"\"type\":\"upstream_error\",\"param\":\"307\"\"\" in error_msg:\n                raise ConnectionAbortedError(\"正常结束，但显示Token不足，导致输出不完整，请削减单次输入的文本量。\")\n            else:\n                raise RuntimeError(\"OpenAI拒绝了请求：\" + error_msg)\n        if ('data: [DONE]' in chunk_decoded): break # api2d 正常完成\n        # 提前读取一些信息 （用于判断异常）\n        json_data = chunkjson['choices'][0]\n        delta = json_data[\"delta\"]\n        if len(delta) == 0: break\n        if (not has_content) and has_role: continue\n        if (not has_content) and (not has_role): continue # raise RuntimeError(\"发现不标准的第三方接口：\"+delta)\n        if has_content: # has_role = True/False\n            result += delta[\"content\"]\n            if not console_silence: print(delta[\"content\"], end='')\n            if observe_window is not None:\n                # 观测窗，把已经获取的数据显示出去\n                if len(observe_window) >= 1:\n                    observe_window[0] += delta[\"content\"]\n                # 看门狗，如果超过期限没有喂狗，则终止\n                if len(observe_window) >= 2:\n                    if (time.time()-observe_window[1]) > watch_dog_patience:\n                        raise RuntimeError(\"用户取消了程序。\")","sourceCodeStart":163,"sourceCodeEnd":199,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/request_llms/bridge_openrouter.py#L163-L199","documentation":"Generic RuntimeError from bridge_openrouter.predict_no_ui_long_connection: the stream produced a frame that does not start with 'data:' and whose drained body (get_full_error) matches neither 'reduce the length' nor the upstream_error/307 signature. The full server error text is appended to the message, so the actionable detail is inside error_msg.","triggerScenarios":"API key rejected (401 body streamed as non-SSE); OpenRouter rate limit (429); model not available for the account; relay returning an HTML/plain error page mid-stream; malformed SSE from a non-standard OpenAI-compatible provider.","commonSituations":"Expired or wrong OPENAI_API_KEY / API_KEY route; using a model ID not enabled on OpenRouter; hitting free-tier rate limits; third-party reverse proxies that break SSE framing.","solutions":["Read the error_msg suffix - it contains the upstream HTTP body (status code and reason)","Verify the API key and that the model ID is valid for the OpenRouter account","If rate-limited (429), back off and retry later or switch to another key via select_api_key rotation","Confirm the provider actually supports SSE streaming; if not, use a non-stream path or different bridge"],"exampleFix":"# before\nresult = predict_no_ui_long_connection(inputs, llm_kwargs, history)\n\n# after\ntry:\n    result = predict_no_ui_long_connection(inputs, llm_kwargs, history)\nexcept RuntimeError as e:\n    if 'OpenAI拒绝了请求' in str(e):\n        log.error('upstream body: %s', str(e).split('请求：')[-1])\n    raise","handlingStrategy":"try-catch","validationCode":"from common_utils import is_any_api_key\nassert is_any_api_key(llm_kwargs['api_key']), 'API key missing/placeholder'\nimport requests\nr = requests.post(api_url, headers=headers, json={'model': model, 'messages': [{'role':'user','content':'ping'}], 'max_tokens': 1}, timeout=15)\nassert r.status_code == 200, f'provider rejected: {r.status_code} {r.text[:200]}'","typeGuard":null,"tryCatchPattern":"try:\n    result = predict_no_ui_long_connection(...)\nexcept RuntimeError as e:\n    msg = str(e)\n    if 'OpenAI拒绝了请求' in msg:\n        body = msg.split('请求：', 1)[-1]\n        if '429' in body:\n            time.sleep(backoff); retry_with_next_key()\n        else:\n            raise ProviderError(body)","preventionTips":["Pre-flight ping the endpoint with a 1-token request before long jobs","Rotate API keys on 429 instead of reusing the same one","Always parse the embedded error body - the RuntimeError text alone is generic"],"tags":["openrouter","api-error","streaming","http-error"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}