binary-husky/gpt_academic · error · RuntimeError

OpenAI拒绝了请求:{error_msg}

Error message

OpenAI拒绝了请求:{error_msg}

What it means

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.

Source

Thrown at request_llms/bridge_openrouter.py:181

    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 or chunk_decoded.startswith(':'): 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 正常完成
        # 提前读取一些信息 (用于判断异常)
        json_data = chunkjson['choices'][0]
        delta = json_data["delta"]
        if len(delta) == 0: break
        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"]
            if not console_silence: print(delta["content"], end='')
            if observe_window is not None:
                # 观测窗,把已经获取的数据显示出去
                if len(observe_window) >= 1:
                    observe_window[0] += delta["content"]
                # 看门狗,如果超过期限没有喂狗,则终止
                if len(observe_window) >= 2:
                    if (time.time()-observe_window[1]) > watch_dog_patience:
                        raise RuntimeError("用户取消了程序。")

View on GitHub (pinned to d6bde0fa54)

Solutions

  1. Read the error_msg suffix - it contains the upstream HTTP body (status code and reason)
  2. Verify the API key and that the model ID is valid for the OpenRouter account
  3. If rate-limited (429), back off and retry later or switch to another key via select_api_key rotation
  4. Confirm the provider actually supports SSE streaming; if not, use a non-stream path or different bridge

Example fix

# before
result = predict_no_ui_long_connection(inputs, llm_kwargs, history)

# after
try:
    result = predict_no_ui_long_connection(inputs, llm_kwargs, history)
except RuntimeError as e:
    if 'OpenAI拒绝了请求' in str(e):
        log.error('upstream body: %s', str(e).split('请求:')[-1])
    raise
Defensive patterns

Strategy: try-catch

Validate before calling

from common_utils import is_any_api_key
assert is_any_api_key(llm_kwargs['api_key']), 'API key missing/placeholder'
import requests
r = requests.post(api_url, headers=headers, json={'model': model, 'messages': [{'role':'user','content':'ping'}], 'max_tokens': 1}, timeout=15)
assert r.status_code == 200, f'provider rejected: {r.status_code} {r.text[:200]}'

Try / catch

try:
    result = predict_no_ui_long_connection(...)
except RuntimeError as e:
    msg = str(e)
    if 'OpenAI拒绝了请求' in msg:
        body = msg.split('请求:', 1)[-1]
        if '429' in body:
            time.sleep(backoff); retry_with_next_key()
        else:
            raise ProviderError(body)

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of binary-husky/gpt_academic@d6bde0fa54 (2026-08-14). Data as JSON: /api/errors/d29ec091b016166d. Report an issue: GitHub.