{"record":{"id":"211a3653240ddef0","repo":"binary-husky/gpt_academic","slug":"gpt-is-not-generating-proper-code","errorCode":null,"errorMessage":"GPT is not generating proper code.","messagePattern":"GPT is not generating proper code\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"crazy_functions/Dynamic_Function_Generate.py","lineNumber":56,"sourceCode":"        ...\n        return generated_file_path\n```\n\"\"\"\n\ndef inspect_dependency(chatbot, history):\n    yield from update_ui(chatbot=chatbot, history=history) # 刷新界面\n    return True\n\ndef get_code_block(reply):\n    import re\n    pattern = r\"```([\\s\\S]*?)```\" # regex pattern to match code blocks\n    matches = re.findall(pattern, reply) # find all code blocks in text\n    if len(matches) == 1:\n        return matches[0].strip('python') #  code block\n    for match in matches:\n        if 'class TerminalFunction' in match:\n            return match.strip('python') #  code block\n    raise RuntimeError(\"GPT is not generating proper code.\")\n\ndef gpt_interact_multi_step(txt, file_type, llm_kwargs, chatbot, history):\n    # 输入\n    prompt_compose = [\n        f'Your job:\\n'\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',\n        f\"2. You should write this function to perform following task: \" + txt + \"\\n\",\n        f\"3. Wrap the output python function with markdown codeblock.\"\n    ]\n    i_say = \"\".join(prompt_compose)\n    demo = []\n\n    # 第一步\n    gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(\n        inputs=i_say, inputs_show_user=i_say,\n        llm_kwargs=llm_kwargs, chatbot=chatbot, history=demo,\n        sys_prompt= r\"You are a world-class programmer.\"\n    )","sourceCodeStart":38,"sourceCodeEnd":74,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/crazy_functions/Dynamic_Function_Generate.py#L38-L74","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Regenerate with a stronger code model and lower temperature.","Ensure the stage-two prompt still contains the template requiring class TerminalFunction and run(self, path).","Retry automatically when no block contains class TerminalFunction, adding an explicit 'return exactly one Python fenced code block' instruction.","Make the parser accept an optional language tag and prefer the block containing the required class.","Inspect the raw gpt_say in the chatbot/log before changing code."],"exampleFix":"# before\nmatches = re.findall(r\"```([\\s\\S]*?)```\", reply)\nif len(matches) == 1:\n    return matches[0].strip('python')\nfor match in matches:\n    if 'class TerminalFunction' in match:\n        return match.strip('python')\nraise RuntimeError(\"GPT is not generating proper code.\")\n\n# after\nmatches = re.findall(r\"```(?:python)?\\s*([\\s\\S]*?)```\", reply)\nfor match in matches:\n    if 'class TerminalFunction' in match:\n        return match\nif len(matches) == 1:\n    return matches[0]\nraise RuntimeError(\"GPT reply has no fenced TerminalFunction implementation\")\n","handlingStrategy":"validation","validationCode":"import re\n\ndef has_terminal_function_block(reply) -> bool:\n    blocks = re.findall(r\"```(?:python)?\\s*([\\s\\S]*?)```\", reply)\n    return any(\"class TerminalFunction\" in block for block in blocks) or len(blocks) == 1\n","typeGuard":"def has_terminal_function_block(reply: str) -> bool:\n    blocks = re.findall(r\"```(?:python)?\\s*([\\s\\S]*?)```\", reply or \"\")\n    return any(\"class TerminalFunction\" in b for b in blocks)\n","tryCatchPattern":"try:\n    code = get_code_block(gpt_say)\nexcept RuntimeError as e:\n    gpt_say = retry_with_feedback(\"Return exactly one fenced Python class named TerminalFunction.\")\n    code = get_code_block(gpt_say)\n","preventionTips":["Request exactly one fenced Python block.","Use a code-capable model with low temperature.","Validate LLM output before executing or importing it.","Keep the required template inside the context window."],"tags":["llm","code-generation","parsing","regex"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}