FoundationAgents/MetaGPT · error · ValueError

`to_replace` must not be empty.

Error message

`to_replace` must not be empty.

What it means

Raised by Editor._edit_file_by_replace when to_replace strips to an empty string but the file has non-whitespace content. An empty search pattern is meaningless for a targeted replace (and str.replace semantics would be dangerous), so the tool requires a concrete snippet to anchor on.

Source

Thrown at metagpt/tools/libs/editor.py:888

            This tool is exclusive. If you use this tool, you cannot use any other commands in the current response.
            If you need to use it multiple times, wait for the next turn.
        """
        # FIXME: support replacing *all* occurrences

        if to_replace == new_content:
            raise ValueError("`to_replace` and `new_content` must be different.")

        # search for `to_replace` in the file
        # if found, replace it with `new_content`
        # if not found, perform a fuzzy search to find the closest match and replace it with `new_content`
        file_name = self._try_fix_path(file_name)
        with file_name.open("r") as file:
            file_content = file.read()

        if to_replace.strip() == "":
            if file_content.strip() == "":
                raise ValueError(f"The file '{file_name}' is empty. Please use the append method to add content.")
            raise ValueError("`to_replace` must not be empty.")

        if file_content.count(to_replace) > 1:
            raise ValueError(
                "`to_replace` appears more than once, please include enough lines to make code in `to_replace` unique."
            )
        start = file_content.find(to_replace)
        if start != -1:
            # Convert start from index to line number
            start_line_number = file_content[:start].count("\n") + 1
            end_line_number = start_line_number + len(to_replace.splitlines()) - 1
        else:

            def _fuzzy_transform(s: str) -> str:
                # remove all space except newline
                return re.sub(r"[^\S\n]+", "", s)

            # perform a fuzzy search (remove all spaces except newlines)
            to_replace_fuzzy = _fuzzy_transform(to_replace)

View on GitHub (pinned to 11cdf466d0)

Solutions

  1. Provide the exact existing code snippet to anchor the replacement
  2. To add content without removing anything, use insert (at a line) or append instead of replace
  3. Validate to_replace.strip() is non-empty in your wrapper before calling

Example fix

// before
editor.edit_file_by_replace(path, to_replace='', new_content='import os\n')  # ValueError

// after
editor.insert_content_at('import os\n', file=path, line_number=1)  # prepend via insert
Defensive patterns

Strategy: validation

Validate before calling

if not to_replace.strip():
    if Path(path).read_text().strip() == '':
        editor.append_file(path, new_content)
    else:
        editor.insert_content_at(new_content, line_number=1)
else:
    editor.edit_file_by_replace(path, to_replace, new_content)

Type guard

def has_anchor(to_replace: str) -> bool:
    return to_replace.strip() != ''

Try / catch

try:
    editor.edit_file_by_replace(path, to_replace, new_content)
except ValueError as e:
    if 'must not be empty' in str(e):
        raise ValueError('to_replace missing — provide the exact snippet to replace')
    raise

Prevention

When it happens

Trigger: editor.edit_file_by_replace(path, to_replace='', new_content=c) or to_replace=' \n' against a file with real content; an LLM omitting the to_replace parameter or sending only whitespace.

Common situations: Tool-call schemas where to_replace is optional and gets defaulted to ''; whitespace-only snippets from bad extraction; prepend attempts mistakenly routed through replace.

Related errors


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