{"record":{"id":"938346afed0cff8f","repo":"FoundationAgents/MetaGPT","slug":"parse-code-error-for-arguments","errorCode":null,"errorMessage":"Parse code error for {arguments}","messagePattern":"Parse code error for (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"metagpt/provider/openai_api.py","lineNumber":225,"sourceCode":"        if \"language\" not in arguments and \"code\" not in arguments:\n            logger.warning(f\"Not found `code`, `language`, We assume it is pure code:\\n {arguments}\\n. \")\n            return {\"language\": \"python\", \"code\": arguments}\n\n        # 匹配language\n        language_pattern = re.compile(r'[\\\"\\']?language[\\\"\\']?\\s*:\\s*[\"\\']([^\"\\']+?)[\"\\']', re.DOTALL)\n        language_match = language_pattern.search(arguments)\n        language_value = language_match.group(1) if language_match else \"python\"\n\n        # 匹配code\n        code_pattern = r'([\"\\'`]{3}|[\"\\'`])([\\s\\S]*?)\\1'\n        try:\n            code_value = re.findall(code_pattern, arguments)[-1][-1]\n        except Exception as e:\n            logger.error(f\"{e}, when re.findall({code_pattern}, {arguments})\")\n            code_value = None\n\n        if code_value is None:\n            raise ValueError(f\"Parse code error for {arguments}\")\n        # arguments只有code的情况\n        return {\"language\": language_value, \"code\": code_value}\n\n    # @handle_exception\n    def get_choice_function_arguments(self, rsp: ChatCompletion) -> dict:\n        \"\"\"Required to provide the first function arguments of choice.\n\n        :param dict rsp: same as in self.get_choice_function(rsp)\n        :return dict: return the first function arguments of choice, for example,\n            {'language': 'python', 'code': \"print('Hello, World!')\"}\n        \"\"\"\n        message = rsp.choices[0].message\n        if (\n            message.tool_calls is not None\n            and message.tool_calls[0].function is not None\n            and message.tool_calls[0].function.arguments is not None\n        ):\n            # reponse is code","sourceCodeStart":207,"sourceCodeEnd":243,"githubUrl":"https://github.com/FoundationAgents/MetaGPT/blob/11cdf466d042aece04fc6cfd13b28e1a70341b1f/metagpt/provider/openai_api.py#L207-L243","documentation":"OpenAIGPTAPI._parse_arguments extracts a code block from a tool-call's arguments using a quote/backtick regex; if no quoted code segment is found (re.findall returned nothing and code_value stays None), it raises ValueError('Parse code error for ...'). The language is defaulted to python, but the code itself is mandatory.","triggerScenarios":"get_choice_function_arguments on a response where tool_calls[0].function.arguments contains code without enclosing quotes/backticks, or arguments that are JSON like {\"language\": \"javascript\"} with the code field missing; the regex finds no quoted payload and the raise fires.","commonSituations":"Weaker models emitting malformed tool-call JSON, truncation at max tokens cutting off the code quotes, or actions whose arguments only carry metadata; typically seen in MetaGPT ActionNode/DataInterpreter tool flows.","solutions":["Retry the completion (a fresh sample usually produces well-formed quoted arguments).","Increase max_token limits so the code block is not truncated mid-quote.","Switch to a stronger model for tool/function calling (arguments format adherence varies).","Catch the ValueError and apply a lenient fallback parser that treats the whole arguments string as code."],"exampleFix":"# before\narguments = '{\"language\": \"python\"}'  # no quoted code -> ValueError\n\n# after (ensure model emits quoted code, or fall back)\ntry:\n    parsed = provider._parse_arguments(arguments)\nexcept ValueError:\n    parsed = {\"language\": \"python\", \"code\": arguments}","handlingStrategy":"try-catch","validationCode":"import re\n\ndef looks_parseable(arguments: str) -> bool:\n    return bool(re.search(r'([\"' + \"'`\" + r']{3}|[\"' + \"'` + r'])([\\s\\S]*?)\\1', arguments))","typeGuard":null,"tryCatchPattern":"try:\n    parsed = provider.get_choice_function_arguments(rsp)\nexcept ValueError as e:\n    if \"Parse code error\" in str(e):\n        args = rsp.choices[0].message.tool_calls[0].function.arguments\n        parsed = {\"language\": \"python\", \"code\": args}  # lenient fallback\n    else:\n        raise","preventionTips":["Use function-calling-capable models for code actions","Raise max_token limits to avoid mid-quote truncation","Implement a lenient fallback parser for unquoted code arguments"],"tags":["openai","tool-calls","parsing","llm-output"],"backgroundTag":null,"analyzedSha":"11cdf466d042aece04fc6cfd13b28e1a70341b1f","analyzedAt":"2026-08-14T23:20:02.994Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}