binary-husky/gpt_academic · error · RuntimeError

意外Json结构:

Error message

意外Json结构:

What it means

RuntimeError ('意外Json结构:' + delta) raised when a streamed delta object parses as JSON, has no 'content' key, and also no 'role' key — i.e. the chunk's delta is neither content nor a role header, which contradicts the OpenAI chat-completions delta schema this bridge implements. The delta payload is appended to the message so the deviant structure is visible. It typically indicates a non-conformant third-party relay injecting extra delta fields.

Source

Thrown at request_llms/bridge_chatgpt.py:215

            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"]
            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("用户取消了程序。")
        else: raise RuntimeError("意外Json结构:"+delta)

    finish_reason = json_data.get('finish_reason', None) if json_data else None
    if finish_reason == 'content_filter':
        raise RuntimeError("由于提问含不合规内容被过滤。")
    if finish_reason == 'length':
        raise ConnectionAbortedError("正常结束,但显示Token不足,导致输出不完整,请削减单次输入的文本量。")

    return result


def predict(inputs:str, llm_kwargs:dict, plugin_kwargs:dict, chatbot:ChatBotWithCookies,
            history:list=[], system_prompt:str='', stream:bool=True, additional_fn:str=None):
    """
    发送至chatGPT,流式获取输出。
    用于基础的对话功能。
    inputs 是本次问询的输入
    top_p, temperature是chatGPT的内部调优参数
    history 是之前的对话列表(注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误)

View on GitHub (pinned to d6bde0fa54)

Solutions

  1. Inspect the printed delta to identify the stray field; if it's reasoning_content or tool-call data, update gpt_academic to a version whose decode_chunk tolerates it.
  2. Switch to the official OpenAI/Azure endpoint to confirm the relay is the source of the malformed delta.
  3. If you control the bridge, extend decode_chunk to accept the extra delta shapes instead of raising (the commented-out line above shows raise was once relaxed).
  4. Disable the non-standard feature (e.g. tool/reasoning mode) on the relay channel serving your key.

Example fix

# before
else: raise RuntimeError("意外Json结构:"+delta)

# after (tolerate known extra keys)
else:
    if any(k in delta for k in ("reasoning_content", "tool_calls", "function_call")):
        continue
    raise RuntimeError("意外Json结构:" + str(delta))
Defensive patterns

Strategy: type-guard

Type guard

def is_standard_chat_delta(delta: dict) -> bool:
    """OpenAI chat-completions deltas carry content or role; anything else is non-standard."""
    return isinstance(delta, dict) and ('content' in delta or 'role' in delta)

Try / catch

try:
    reply = predict_no_ui_long_connection(...)
except RuntimeError as e:
    if '意外Json结构' in str(e):
        log_nonstandard_delta(str(e))  # inspect which key the relay added
        switch_to_official_endpoint()
    else:
        raise

Prevention

When it happens

Trigger: A relay/one-api channel forwards deltas containing only unexpected keys (e.g. {'reasoning_content': ...} without 'content', tool-call deltas, or vendor-specific fields) so decode_chunk sets has_content=False and has_role=False; the else branch then fires. Only reached when the chunk DID parse as choices-bearing JSON, so it is a schema mismatch, not a transport error.

Common situations: Third-party OpenAI-compatible gateways that add fields like reasoning_content, function_call, or empty deltas; newer model APIs (tool calling, o1-style reasoning) streamed through bridges that predate those delta types; partially-conforming one-api channels.

Related errors


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