{"record":{"id":"138790136536c570","repo":"binary-husky/gpt_academic","slug":"openai-138790","errorCode":null,"errorMessage":"OpenAI拒绝了请求：","messagePattern":"OpenAI拒绝了请求：","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"request_llms/bridge_chatgpt.py","lineNumber":187,"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: 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 & one-api 正常完成\n        # 提前读取一些信息 （用于判断异常）\n        if has_choices and not choice_valid:\n            # 一些垃圾第三方接口的出现这样的错误\n            continue\n        json_data = chunkjson['choices'][0]\n        delta = json_data[\"delta\"]\n\n        if len(delta) == 0:\n            is_termination_certain = False\n            if (has_choices) and (chunkjson['choices'][0].get('finish_reason', 'null') == 'stop'): is_termination_certain = True\n            if is_termination_certain: break\n            else: continue # 对于不符合规范的狗屎接口，这里需要继续\n\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\"]","sourceCodeStart":169,"sourceCodeEnd":205,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/request_llms/bridge_chatgpt.py#L169-L205","documentation":"A catch-all RuntimeError ('OpenAI拒绝了请求：' + full error text) raised when the streaming response's first non-empty chunk does not start with 'data:' and the recovered error body matches neither 'reduce the length' nor the upstream_error/307 pattern. It means the server (OpenAI, Azure, or a relay) rejected the request and returned a plain error payload instead of an SSE stream. The appended error_msg carries the actual server reason — always read it.","triggerScenarios":"Invalid/expired API key (401), wrong model name (404 model_not_found), insufficient quota (429), Azure deployment mismatch, malformed base URL, or a relay returning HTML/JSON error pages — any case where decode_chunk gets a chunk not prefixed with 'data:' and get_full_error extracts a body that is not one of the two recognized patterns.","commonSituations":"Typo'd or revoked API key; using a model name the endpoint doesn't serve (e.g. asking a relay for gpt-4 when only gpt-3.5 is bound); free-trial key quota exhausted; wrong API url scheme (using /v1/chat vs deployment paths); Cloudflare HTML error pages from misconfigured proxies.","solutions":["Read the appended error text in the exception message — it contains the server's own reason (401/404/429 etc.) and dictates the fix.","401/invalid key: set a valid API_KEY in config_private.py or type it into the input box and press Enter.","404/model not found: correct LLM_MODEL to a model your endpoint actually serves (check model_info in request_llms/bridge_all.py).","429/quota: add billing to the key, wait out the rate window, or configure multiple keys (API_KEY = \"sk-...,sk-...\") for rotation.","If the body is HTML, your API_URL_REDIRECT is pointing at the wrong path — verify the endpoint URL format."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"import requests\nresp = requests.get(api_url + \"/models\", headers={\"Authorization\": f\"Bearer {api_key}\"}, timeout=10)\nassert resp.status_code == 200, f\"endpoint rejected preflight: {resp.status_code} {resp.text[:200]}\"","typeGuard":null,"tryCatchPattern":"try:\n    reply = predict_no_ui_long_connection(...)\nexcept RuntimeError as e:\n    msg = str(e)\n    if 'OpenAI拒绝了请求' in msg:\n        body = msg.split('OpenAI拒绝了请求：', 1)[-1]\n        classify_and_report(body)  # 401 -> key, 404 -> model name, 429 -> quota/rate\n    else:\n        raise","preventionTips":["Preflight the endpoint with a cheap /models call when config changes.","Keep LLM_MODEL names aligned with what the endpoint serves; test after every provider change.","Rotate keys on 429s and cap request frequency client-side.","Always surface the appended server body — it contains the actionable reason."],"tags":["openai","api-error","streaming","configuration","http"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}