{"record":{"id":"685b065bc2fe357f","repo":"binary-husky/gpt_academic","slug":"openai","errorCode":null,"errorMessage":"OpenAI拒绝了请求:","messagePattern":"OpenAI拒绝了请求:","errorType":"exception","errorClass":"ConnectionAbortedError","httpStatus":null,"severity":"error","filePath":"request_llms/bridge_chatgpt.py","lineNumber":183,"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: 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","sourceCodeStart":165,"sourceCodeEnd":201,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/request_llms/bridge_chatgpt.py#L165-L201","documentation":"Raised as ConnectionAbortedError when the OpenAI-compatible stream returns a non-SSE frame and get_full_error recovers an error body containing 'reduce the length'. This is OpenAI's context-length rejection: the combined prompt (inputs + history + system prompt) exceeds the model's token limit, so the API refuses the request before generating. The bridge surfaces it as a distinct exception type so callers can react to overflow specifically.","triggerScenarios":"Calling predict_no_ui_long_connection / predict with a history + inputs + system_prompt whose total tokens exceed the selected model's context window (e.g. 4096/8192/16384 depending on model); long-document plugins (arXiv translation, full-text reading) feeding oversized chunks; the non-data first chunk from the stream carries the error and 'reduce the length' appears in the body.","commonSituations":"Long conversations accumulated in history; using gpt-3.5-turbo-0301/0613 style 4k models against big paper PDFs; third-party one-api relays that map upstream overflow errors into plain-text bodies; forgetting that system_prompt also counts toward the limit.","solutions":["Shorten the input: clear or trim the chat history, or reduce the document chunk size the plugin feeds.","Switch to a larger-context model (e.g. gpt-4-32k, gpt-4-turbo, gpt-4o) via the model dropdown / LLM_MODEL in config_private.py.","If you maintain the calling plugin, implement sliding-window truncation of history so total tokens stay under the model limit.","Check model_info[ELEMENT]['max_token'] in request_llms/bridge_all.py matches the model you actually deployed, especially on Azure/relay endpoints."],"exampleFix":"# before\ninputs = full_paper_text  # 100k tokens into a 4k model\n\n# after\nmax_tokens = model_info[llm_kwargs['llm_model']]['max_token']\ninputs = full_paper_text[: max_tokens * 3]  # rough chars-per-token cut, keep under limit","handlingStrategy":"fallback","validationCode":"from request_llms.bridge_all import model_info\ninfo = model_info[llm_kwargs['llm_model']]\n# rough guard: chars/3 approximates tokens for mixed text\nest_tokens = (len(inputs) + sum(len(a)+len(b) for a, b in history) + len(sys_prompt)) // 3\nassert est_tokens < info['max_token'] * 0.9, f\"input ~{est_tokens} tokens near limit {info['max_token']}\"","typeGuard":null,"tryCatchPattern":"try:\n    reply = predict_no_ui_long_connection(...)\nexcept ConnectionAbortedError as e:\n    if 'reduce the length' in str(e):\n        history = history[-2:]  # shrink context and retry once\n        reply = predict_no_ui_long_connection(inputs, llm_kwargs, history, sys_prompt, observe_window)\n    else:\n        raise","preventionTips":["Track conversation token count client-side and trim history before it approaches the model limit.","Prefer models with 32k+ context for document-heavy plugins.","Keep model_info max_token entries in sync with the endpoint you actually deploy.","Treat ConnectionAbortedError from these bridges as 'reduce input' semantics and degrade gracefully."],"tags":["openai","context-length","tokens","streaming","configuration"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}