FoundationAgents/MetaGPT · error · ValueError

Parse code error for {arguments}

Error message

Parse code error for {arguments}

What it means

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.

Source

Thrown at metagpt/provider/openai_api.py:225

        if "language" not in arguments and "code" not in arguments:
            logger.warning(f"Not found `code`, `language`, We assume it is pure code:\n {arguments}\n. ")
            return {"language": "python", "code": arguments}

        # 匹配language
        language_pattern = re.compile(r'[\"\']?language[\"\']?\s*:\s*["\']([^"\']+?)["\']', re.DOTALL)
        language_match = language_pattern.search(arguments)
        language_value = language_match.group(1) if language_match else "python"

        # 匹配code
        code_pattern = r'(["\'`]{3}|["\'`])([\s\S]*?)\1'
        try:
            code_value = re.findall(code_pattern, arguments)[-1][-1]
        except Exception as e:
            logger.error(f"{e}, when re.findall({code_pattern}, {arguments})")
            code_value = None

        if code_value is None:
            raise ValueError(f"Parse code error for {arguments}")
        # arguments只有code的情况
        return {"language": language_value, "code": code_value}

    # @handle_exception
    def get_choice_function_arguments(self, rsp: ChatCompletion) -> dict:
        """Required to provide the first function arguments of choice.

        :param dict rsp: same as in self.get_choice_function(rsp)
        :return dict: return the first function arguments of choice, for example,
            {'language': 'python', 'code': "print('Hello, World!')"}
        """
        message = rsp.choices[0].message
        if (
            message.tool_calls is not None
            and message.tool_calls[0].function is not None
            and message.tool_calls[0].function.arguments is not None
        ):
            # reponse is code

View on GitHub (pinned to 11cdf466d0)

Solutions

  1. Retry the completion (a fresh sample usually produces well-formed quoted arguments).
  2. Increase max_token limits so the code block is not truncated mid-quote.
  3. Switch to a stronger model for tool/function calling (arguments format adherence varies).
  4. Catch the ValueError and apply a lenient fallback parser that treats the whole arguments string as code.

Example fix

# before
arguments = '{"language": "python"}'  # no quoted code -> ValueError

# after (ensure model emits quoted code, or fall back)
try:
    parsed = provider._parse_arguments(arguments)
except ValueError:
    parsed = {"language": "python", "code": arguments}
Defensive patterns

Strategy: try-catch

Validate before calling

import re

def looks_parseable(arguments: str) -> bool:
    return bool(re.search(r'(["' + "'`" + r']{3}|["' + "'` + r'])([\s\S]*?)\1', arguments))

Try / catch

try:
    parsed = provider.get_choice_function_arguments(rsp)
except ValueError as e:
    if "Parse code error" in str(e):
        args = rsp.choices[0].message.tool_calls[0].function.arguments
        parsed = {"language": "python", "code": args}  # lenient fallback
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of FoundationAgents/MetaGPT@11cdf466d0 (2026-08-14). Data as JSON: /api/errors/938346afed0cff8f. Report an issue: GitHub.