binary-husky/gpt_academic · error · RuntimeError

GPT is not generating proper code.

Error message

GPT is not generating proper code.

What it means

get_code_block() parses the LLM answer with the regex ```([\s\S]*?)``` and expects either exactly one fenced block or at least one block containing class TerminalFunction. This RuntimeError means the reply had no fenced block, or none of the fenced blocks implemented the required class.

Source

Thrown at crazy_functions/Dynamic_Function_Generate.py:56

        ...
        return generated_file_path
```
"""

def inspect_dependency(chatbot, history):
    yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
    return True

def get_code_block(reply):
    import re
    pattern = r"```([\s\S]*?)```" # regex pattern to match code blocks
    matches = re.findall(pattern, reply) # find all code blocks in text
    if len(matches) == 1:
        return matches[0].strip('python') #  code block
    for match in matches:
        if 'class TerminalFunction' in match:
            return match.strip('python') #  code block
    raise RuntimeError("GPT is not generating proper code.")

def gpt_interact_multi_step(txt, file_type, llm_kwargs, chatbot, history):
    # 输入
    prompt_compose = [
        f'Your job:\n'
        f'1. write a single Python function, which takes a path of a `{file_type}` file as the only argument and returns a `string` containing the result of analysis or the path of generated files. \n',
        f"2. You should write this function to perform following task: " + txt + "\n",
        f"3. Wrap the output python function with markdown codeblock."
    ]
    i_say = "".join(prompt_compose)
    demo = []

    # 第一步
    gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
        inputs=i_say, inputs_show_user=i_say,
        llm_kwargs=llm_kwargs, chatbot=chatbot, history=demo,
        sys_prompt= r"You are a world-class programmer."
    )

View on GitHub (pinned to d6bde0fa54)

Solutions

  1. Regenerate with a stronger code model and lower temperature.
  2. Ensure the stage-two prompt still contains the template requiring class TerminalFunction and run(self, path).
  3. Retry automatically when no block contains class TerminalFunction, adding an explicit 'return exactly one Python fenced code block' instruction.
  4. Make the parser accept an optional language tag and prefer the block containing the required class.
  5. Inspect the raw gpt_say in the chatbot/log before changing code.

Example fix

# before
matches = re.findall(r"```([\s\S]*?)```", reply)
if len(matches) == 1:
    return matches[0].strip('python')
for match in matches:
    if 'class TerminalFunction' in match:
        return match.strip('python')
raise RuntimeError("GPT is not generating proper code.")

# after
matches = re.findall(r"```(?:python)?\s*([\s\S]*?)```", reply)
for match in matches:
    if 'class TerminalFunction' in match:
        return match
if len(matches) == 1:
    return matches[0]
raise RuntimeError("GPT reply has no fenced TerminalFunction implementation")
Defensive patterns

Strategy: validation

Validate before calling

import re

def has_terminal_function_block(reply) -> bool:
    blocks = re.findall(r"```(?:python)?\s*([\s\S]*?)```", reply)
    return any("class TerminalFunction" in block for block in blocks) or len(blocks) == 1

Type guard

def has_terminal_function_block(reply: str) -> bool:
    blocks = re.findall(r"```(?:python)?\s*([\s\S]*?)```", reply or "")
    return any("class TerminalFunction" in b for b in blocks)

Try / catch

try:
    code = get_code_block(gpt_say)
except RuntimeError as e:
    gpt_say = retry_with_feedback("Return exactly one fenced Python class named TerminalFunction.")
    code = get_code_block(gpt_say)

Prevention

When it happens

Trigger: The second GPT stage omits markdown fences, replies with prose or a refusal, returns several example blocks but none named TerminalFunction, uses ~~~ fences, or truncates before the class body.

Common situations: Using a weak or non-code model; temperature is high; the prompt/history was clipped so the template was lost; the model explains the function instead of rewriting it; a proxy returns an error message instead of model output.

Related errors


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