binary-husky/gpt_academic · error · RuntimeError

{gpt_replying_buffer} 对话错误

Error message

{gpt_replying_buffer} 对话错误

What it means

Raised when the raw Gemini SSE payload matches the regex '"message":\s*"(.*?)"', i.e. the response chunk contains an API error object (e.g. quota, safety, invalid API key) instead of generated text. The accumulated partial buffer is prefixed to the message so the caller can see how far generation got before the error.

Source

Thrown at request_llms/bridge_google_gemini.py:44

    gpt_replying_buffer = ''
    stream_response = genai.generate_chat(inputs, llm_kwargs, history, sys_prompt)
    for response in stream_response:
        results = response.decode()
        match = re.search(r'"text":\s*"((?:[^"\\]|\\.)*)"', results, flags=re.DOTALL)
        error_match = re.search(r'\"message\":\s*\"(.*?)\"', results, flags=re.DOTALL)
        if match:
            try:
                paraphrase = json.loads('{"text": "%s"}' % match.group(1))
            except:
                raise ValueError(f"解析GEMINI消息出错。")
            buffer = paraphrase['text']
            gpt_replying_buffer += buffer
            if len(observe_window) >= 1:
                observe_window[0] = gpt_replying_buffer
            if len(observe_window) >= 2:
                if (time.time() - observe_window[1]) > watch_dog_patience: raise RuntimeError("程序终止。")
        if error_match:
            raise RuntimeError(f'{gpt_replying_buffer} 对话错误')
    return gpt_replying_buffer

def make_media_input(inputs, image_paths):
    image_base64_array = []
    for image_path in image_paths:
        path = os.path.abspath(image_path)
        inputs = inputs + f'<br/><br/><div align="center"><img src="file={path}"></div>'
        base64 = encode_image(path)
        image_base64_array.append(base64)
    return inputs, image_base64_array

def predict(inputs:str, llm_kwargs:dict, plugin_kwargs:dict, chatbot:ChatBotWithCookies,
            history:list=[], system_prompt:str='', stream:bool=True, additional_fn:str=None):

    from .bridge_all import model_info

    # 检查API_KEY
    if get_conf("GEMINI_API_KEY") == "":

View on GitHub (pinned to d6bde0fa54)

Solutions

  1. Print/inspect the full raw `results` payload — the '(.*?)' group captured the actual API message; fix the root cause it names (key, quota, safety).
  2. Verify GEMINI_API_KEY is set and valid with a minimal curl request to the API.
  3. If 429/quota: back off, reduce request rate, or switch model tier.
  4. If safety-triggered: rephrase the prompt or handle the refusal gracefully instead of raising.

Example fix

// before
if error_match:
    raise RuntimeError(f'{gpt_replying_buffer} 对话错误')

# after
if error_match:
    raise RuntimeError(f'{gpt_replying_buffer} 对话错误: {error_match.group(1)}')
Defensive patterns

Strategy: try-catch

Try / catch

try:
    out = predict_no_ui_long_connection(...)
except RuntimeError as e:
    if '对话错误' in str(e):
        api_msg = str(e).split('对话错误')[0]  # partial buffer; inspect raw stream for the "message" field
        log.error('Gemini API error: %s', api_msg)

Prevention

When it happens

Trigger: Gemini returns an error JSON body inside the stream (API key rejected, 429 quota exceeded, safety block, malformed request) and the bridge's error_match regex fires; the raise happens with '{buffer} 对话错误'.

Common situations: Expired or wrong GEMINI_API_KEY, hitting free-tier RPM limits, prompt flagged by safety filters, or a region/proxy that returns an error message payload instead of SSE deltas.

Related errors


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