{"record":{"id":"ea43b08560371faa","repo":"binary-husky/gpt_academic","slug":"openai-error-msg","errorCode":null,"errorMessage":"OpenAI拒绝了请求:{error_msg}","messagePattern":"OpenAI拒绝了请求:(.+?)","errorType":"exception","errorClass":"ConnectionAbortedError","httpStatus":null,"severity":"error","filePath":"request_llms/bridge_openrouter.py","lineNumber":177,"sourceCode":"        chunkjson = json.loads(response.content.decode())\n        gpt_replying_buffer = chunkjson['choices'][0][\"message\"][\"content\"]\n        return gpt_replying_buffer\n\n    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\"]","sourceCodeStart":159,"sourceCodeEnd":195,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/request_llms/bridge_openrouter.py#L159-L195","documentation":"ConnectionAbortedError raised in bridge_openrouter.predict_no_ui_long_connection when a non-'data:' stream frame is received and the drained error text contains 'reduce the length' - the upstream's token-limit rejection. The bridge maps that substring to this exception so callers can treat it as context-overflow rather than a generic failure.","triggerScenarios":"history plus inputs exceeding the model's context window so the API rejects the request; a long document plugin (e.g. paper reading) feeding too much text; a third-party OpenAI-compatible relay that forwards OpenAI's 'Please reduce the length of the messages' error verbatim.","commonSituations":"Summarizing very long PDFs; accumulated chat history growing past the model context; routing through OpenRouter to a model with a smaller window than expected.","solutions":["Trim history or shorten inputs so total tokens fit the model's context window","Switch llm_kwargs['llm_model'] to a model with a larger context window","Use the project's history-compression / split-input plugin instead of one giant prompt","Catch ConnectionAbortedError and show a 'reduce input' message to the user instead of retrying (retrying the same payload will fail identically)"],"exampleFix":"# before\nhistory += [long_doc, reply]  # keeps growing\n\n# after\nMAX_TURNS = 8\nhistory = history[-MAX_TURNS*2:]  # bound the context","handlingStrategy":"try-catch","validationCode":"# estimate token count before sending\napprox_tokens = len(inputs) // 2 + sum(len(a) + len(b) for a, b in history) // 2\nmax_ctx = model_info[llm_kwargs['llm_model']].get('max_context', 8000)\nassert approx_tokens < max_ctx * 0.9, f'input ~{approx_tokens} tokens exceeds safe budget {max_ctx}'","typeGuard":null,"tryCatchPattern":"try:\n    result = predict_no_ui_long_connection(inputs, llm_kwargs, history)\nexcept ConnectionAbortedError as e:\n    if 'reduce the length' in str(e):\n        history = history[-6:]  # shrink context and retry once\n        result = predict_no_ui_long_connection(inputs, llm_kwargs, history)\n    else:\n        raise","preventionTips":["Bound conversation history length before each request","Split long documents into chunked summarization instead of one prompt","Never blind-retry on this error - the identical payload will fail again"],"tags":["openrouter","tokens","context-length","streaming"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}