deepset-ai/haystack · error · ValueError

Invalid MIME type or regex pattern '{mime_type}'.

Error message

Invalid MIME type or regex pattern '{mime_type}'.

What it means

FileTypeRouter.__init__ treats each mime_types entry as either a known MIME type (via mimetypes.guess_type) or a regular expression; if re.compile fails because the string is not valid regex, this ValueError is raised, chaining the original re.error.

Source

Thrown at haystack/components/routers/file_type_router.py:93

            (for example: `{"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"}`).

        :param raise_on_failure:
            If True, raises FileNotFoundError when a file path doesn't exist.
            If False (default), only emits a warning when a file path doesn't exist.
        """
        if not mime_types:
            raise ValueError("The list of mime types cannot be empty.")

        if additional_mimetypes:
            for mime, ext in additional_mimetypes.items():
                mimetypes.add_type(mime, ext)

        self.mime_type_patterns = []
        for mime_type in mime_types:
            try:
                pattern = re.compile(mime_type)
            except re.error as e:
                raise ValueError(f"Invalid MIME type or regex pattern '{mime_type}'.") from e
            self.mime_type_patterns.append(pattern)

        # the actual output type is list[Union[Path, ByteStream]],
        # but this would cause PipelineConnectError with Converters
        component.set_output_types(
            self,
            unclassified=list[str | Path | ByteStream],
            failed=list[str | Path | ByteStream],
            **dict.fromkeys(mime_types, list[str | Path | ByteStream]),
        )
        self.mime_types = mime_types
        self._additional_mimetypes = additional_mimetypes
        self._raise_on_failure = raise_on_failure

    def to_dict(self) -> dict[str, Any]:
        """
        Serializes the component to a dictionary.

View on GitHub (pinned to e318778c9b)

Solutions

  1. Correct the pattern to valid regex or a standard MIME type string
  2. Escape regex metacharacters, e.g. 'text\\/(plain|html)' if you need alternation
  3. Verify with re.compile(your_string) before constructing the router

Example fix

# before
router = FileTypeRouter(mime_types=["application/(pdf"])
# after
router = FileTypeRouter(mime_types=["application/pdf", "application/(pdf|zip)"])
Defensive patterns

Strategy: validation

Validate before calling

import re, mimetypes
for mt in mime_types:
    if mimetypes.guess_type("x" + (mimetypes.guess_extension(mt) or ""))[0] is None:
        re.compile(mt)  # not a known MIME type; must be valid regex

Type guard

def is_valid_mime_pattern(mime_type: str) -> bool:
    import re
    try:
        re.compile(mime_type)
        return True
    except re.error:
        return False

Try / catch

try:
    router = FileTypeRouter(mime_types=mime_types)
except ValueError as e:
    if "Invalid MIME type or regex" in str(e):
        mime_types = [mt for mt in mime_types if is_valid_mime_pattern(mt)]
        router = FileTypeRouter(mime_types=mime_types)
    else:
        raise

Prevention

When it happens

Trigger: Passing malformed patterns like 'application/(pdf' or 'text[/plain' to FileTypeRouter(mime_types=[...]).

Common situations: Typos in MIME type lists; regex characters left unescaped; mixing shell-glob syntax with regex syntax.

Related errors


AI-assisted analysis of deepset-ai/haystack@e318778c9b (2026-08-30). Data as JSON: /api/errors/ac5580a263627615. Report an issue: GitHub.