{"record":{"id":"82d6446a1a6b5133","repo":"binary-husky/gpt_academic","slug":"token-82d644","errorCode":null,"errorMessage":"正常结束，但显示Token不足，导致输出不完整，请削减单次输入的文本量。","messagePattern":"正常结束，但显示Token不足，导致输出不完整，请削减单次输入的文本量。","errorType":"exception","errorClass":"ConnectionAbortedError","httpStatus":null,"severity":"error","filePath":"request_llms/bridge_openrouter.py","lineNumber":179,"sourceCode":"        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\"]\n                # 看门狗，如果超过期限没有喂狗，则终止\n                if len(observe_window) >= 2:","sourceCodeStart":161,"sourceCodeEnd":197,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/request_llms/bridge_openrouter.py#L161-L197","documentation":"ConnectionAbortedError from bridge_openrouter when the error body drained from the stream contains type\":\"upstream_error\",\"param\":\"307 - OpenRouter's signal that the upstream provider finished but the response was truncated because the token budget ran out. The bridge converts it into a 'normally finished but token-insufficient' user message.","triggerScenarios":"OpenRouter routing to an upstream that hits its max_tokens mid-generation; max_tokens set lower than needed for the answer; upstream provider quota/budget exhaustion surfaced as upstream_error 307.","commonSituations":"Using OpenRouter with default low max_tokens; long code-generation answers cut off; upstream free-tier providers with tight output limits.","solutions":["Raise the max_tokens / max_output_tokens value in llm_kwargs for this model","Reduce the prompt size so more of the budget is available for output","Switch to a different OpenRouter provider for the same model (the :nitx/:free variants often have tighter limits)","Catch ConnectionAbortedError and re-ask for a shorter, chunked answer"],"exampleFix":"# before\nllm_kwargs['max_tokens'] = 512\n\n# after\nllm_kwargs['max_tokens'] = 4096","handlingStrategy":"try-catch","validationCode":"assert int(llm_kwargs.get('max_tokens', 0) or 0) >= 2048, \\\n    'max_tokens too low for OpenRouter upstream, truncation likely'","typeGuard":null,"tryCatchPattern":"try:\n    result = predict_no_ui_long_connection(...)\nexcept ConnectionAbortedError:\n    # upstream_error 307: output truncated at token budget\n    llm_kwargs['max_tokens'] = min(llm_kwargs['max_tokens'] * 2, model_max)\n    result = predict_no_ui_long_connection(...)","preventionTips":["Set max_tokens near the model's output ceiling for generation-heavy tasks","Prefer paid OpenRouter providers over free variants for long outputs","Keep the partial buffer from observe_window[0] so truncated work is not lost"],"tags":["openrouter","upstream-error","max-tokens","truncation"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}