{"record":{"id":"a9c831714673921a","repo":"binary-husky/gpt_academic","slug":"gpt-is-not-generating-proper-code-a9c831","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/Math_Animation_Gen.py","lineNumber":50,"sourceCode":"        time_str = gen_time_str()\n        subprocess.check_output([sys.executable, '-c', f\"from gpt_log.MyAnimation import {class_name}; {class_name}().render()\"])\n        shutil.move(f'media/videos/1080p60/{class_name}.mp4', f'gpt_log/{class_name}-{time_str}.mp4')\n        return f'gpt_log/{time_str}.mp4'\n    except subprocess.CalledProcessError as e:\n        output = e.output.decode()\n        logger.error(f\"Command returned non-zero exit status {e.returncode}: {output}.\")\n        return f\"Evaluating python script failed: {e.output}.\"\n    except:\n        logger.error('generating mp4 failed')\n        return \"Generating mp4 failed.\"\n\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        raise RuntimeError(\"GPT is not generating proper code.\")\n    return matches[0].strip('python') #  code block\n\n@CatchException\ndef 动画生成(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, user_request):\n    \"\"\"\n    txt             输入栏用户输入的文本，例如需要翻译的一段话，再例如一个包含了待处理文件的路径\n    llm_kwargs      gpt模型参数，如温度和top_p等，一般原样传递下去就行\n    plugin_kwargs   插件模型的参数，暂时没有用武之地\n    chatbot         聊天显示框的句柄，用于显示给用户\n    history         聊天历史，前情提要\n    system_prompt   给gpt的静默提醒\n    user_request    当前用户的请求信息（IP地址等）\n    \"\"\"\n    # 清空历史，以免输入溢出\n    history = []\n\n    # 基本信息：功能、贡献者\n    chatbot.append([","sourceCodeStart":32,"sourceCodeEnd":68,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/crazy_functions/Math_Animation_Gen.py#L32-L68","documentation":"The Manim plugin requires the LLM reply to contain exactly one fenced code block. get_code_block() raises when re.findall finds zero blocks or more than one. Unlike the dynamic-function parser, it does not search multiple blocks for a Scene class.","triggerScenarios":"The model wraps zero or multiple snippets in ``` fences, adds a second example or output block, replies with prose/refusal, or uses ~~~ fences.","commonSituations":"The prompt/history already contains example code blocks and the model echoes them; a weak model ignores the one-block instruction; output is truncated; high temperature produces extra examples.","solutions":["Regenerate with a stronger code model and lower temperature.","Strengthen the system prompt: return exactly one Python block starting with from manim import *.","Prefer a block that defines a manim Scene instead of failing merely because there is more than one.","Validate the response before calling eval_manim and retry once with feedback.","Inspect the raw gpt_say to distinguish model formatting from a proxy error."],"exampleFix":"# before\nmatches = re.findall(r\"```([\\s\\S]*?)```\", reply)\nif len(matches) != 1:\n    raise RuntimeError(\"GPT is not generating proper code.\")\nreturn matches[0].strip('python')\n\n# after\nmatches = re.findall(r\"```(?:python)?\\s*([\\s\\S]*?)```\", reply)\nscene_blocks = [m for m in matches if re.search(r\"class\\s+\\w+\\s*\\(\\s*Scene\\s*\\)\", m)]\nif len(scene_blocks) == 1:\n    return scene_blocks[0]\nif len(matches) == 1:\n    return matches[0]\nraise RuntimeError(f\"GPT reply contains {len(matches)} code blocks and no unique Scene\")\n","handlingStrategy":"validation","validationCode":"import re\n\ndef has_single_manim_block(reply) -> bool:\n    return len(re.findall(r\"```(?:python)?\\s*([\\s\\S]*?)```\", reply)) == 1\n","typeGuard":"def has_manim_scene(reply: str) -> bool:\n    blocks = re.findall(r\"```(?:python)?\\s*([\\s\\S]*?)```\", reply or \"\")\n    return any(re.search(r\"class\\s+\\w+\\s*\\(\\s*Scene\\s*\\)\", block) for block in blocks)\n","tryCatchPattern":"try:\n    code = get_code_block(gpt_say)\nexcept RuntimeError:\n    gpt_say = yield from request_manim_rewrite(gpt_say)\n    code = get_code_block(gpt_say)\n","preventionTips":["Ask for exactly one complete Python fenced block.","Remove extra example blocks from the active prompt if the model echoes them.","Use a code-capable model for Manim generation.","Validate that a Scene class exists before rendering."],"tags":["llm","manim","code-generation","parsing"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}