binary-husky/gpt_academic · error · RuntimeError
OpenAI拒绝了请求:
Error message
OpenAI拒绝了请求:
What it means
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.
Source
Thrown at request_llms/bridge_chatgpt.py:187
stream_response = response.iter_lines()
result = ''
json_data = None
while True:
try: chunk = next(stream_response)
except StopIteration:
break
except requests.exceptions.ConnectionError:
chunk = next(stream_response) # 失败了,重试一次?再失败就没办法了。
chunk_decoded, chunkjson, has_choices, choice_valid, has_content, has_role = decode_chunk(chunk)
if len(chunk_decoded)==0: continue
if not chunk_decoded.startswith('data:'):
error_msg = get_full_error(chunk, stream_response).decode()
if "reduce the length" in error_msg:
raise ConnectionAbortedError("OpenAI拒绝了请求:" + error_msg)
elif """type":"upstream_error","param":"307""" in error_msg:
raise ConnectionAbortedError("正常结束,但显示Token不足,导致输出不完整,请削减单次输入的文本量。")
else:
raise RuntimeError("OpenAI拒绝了请求:" + error_msg)
if ('data: [DONE]' in chunk_decoded): break # api2d & one-api 正常完成
# 提前读取一些信息 (用于判断异常)
if has_choices and not choice_valid:
# 一些垃圾第三方接口的出现这样的错误
continue
json_data = chunkjson['choices'][0]
delta = json_data["delta"]
if len(delta) == 0:
is_termination_certain = False
if (has_choices) and (chunkjson['choices'][0].get('finish_reason', 'null') == 'stop'): is_termination_certain = True
if is_termination_certain: break
else: continue # 对于不符合规范的狗屎接口,这里需要继续
if (not has_content) and has_role: continue
if (not has_content) and (not has_role): continue # raise RuntimeError("发现不标准的第三方接口:"+delta)
if has_content: # has_role = True/False
result += delta["content"]View on GitHub (pinned to d6bde0fa54)
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.
Defensive patterns
Strategy: try-catch
Validate before calling
import requests
resp = requests.get(api_url + "/models", headers={"Authorization": f"Bearer {api_key}"}, timeout=10)
assert resp.status_code == 200, f"endpoint rejected preflight: {resp.status_code} {resp.text[:200]}" Try / catch
try:
reply = predict_no_ui_long_connection(...)
except RuntimeError as e:
msg = str(e)
if 'OpenAI拒绝了请求' in msg:
body = msg.split('OpenAI拒绝了请求:', 1)[-1]
classify_and_report(body) # 401 -> key, 404 -> model name, 429 -> quota/rate
else:
raise Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- OpenAI拒绝了请求:
- API异常,请检测终端输出。可能的原因是:{finish_reason}
- response.content.decode()
- 在线搜索失败,状态码: {response.status_code}\t{response.content.decode
- AZURE_CFG_ARRAY中配置的模型必须以azure开头
AI-assisted analysis of binary-husky/gpt_academic@d6bde0fa54 (2026-08-14).
Data as JSON: /api/errors/138790136536c570.
Report an issue: GitHub.