agentscope-ai/agentscope · error · ValueError

Failed to parse {filename!r} as PDF: {e}

Error message

Failed to parse {filename!r} as PDF: {e}

What it means

pypdf's PdfReader threw PdfReadError while opening the bytes, meaning the data is not a valid PDF (or is corrupted/encrypted malformed). The parser wraps it in ValueError naming the filename and underlying cause.

Source

Thrown at src/agentscope/rag/_parser/_pdf.py:78

        """
        if isinstance(file, str):
            with open(file, "rb") as fp:
                file = fp.read()

        try:
            from pypdf import PdfReader
            from pypdf.errors import PdfReadError
        except ImportError as e:
            raise ImportError(
                "Please install pypdf to use the PDF parser. "
                "You can install it by `pip install pypdf` (or "
                "`pip install agentscope[rag]`).",
            ) from e

        try:
            reader = PdfReader(io.BytesIO(file))
        except PdfReadError as e:
            raise ValueError(
                f"Failed to parse {filename!r} as PDF: {e}",
            ) from e

        sections: list[Section] = []
        for page_idx, page in enumerate(reader.pages, start=1):
            text = page.extract_text() or ""
            sections.append(
                Section(
                    content=TextBlock(text=text),
                    source=filename,
                    metadata={"page": page_idx},
                ),
            )
        return sections

View on GitHub (pinned to e90f1c7592)

Solutions

  1. Verify the file starts with %PDF- magic bytes and opens in a PDF viewer
  2. Re-download/regenerate the source file if truncated
  3. If the PDF is encrypted, decrypt it first (pikepdf/qpdf) before parsing
  4. Sniff content type before routing to PDFParser instead of trusting extensions

Example fix

# before
PDFParser().parse('report.pdf')  # actually HTML

# after
with open('report.pdf','rb') as f:
    head = f.read(5)
assert head == b'%PDF-', 'not a PDF'  # route to correct parser
PDFParser().parse('report.pdf')
Defensive patterns

Strategy: validation

Validate before calling

def is_pdf(data: bytes) -> bool:
    return data[:5] == b'%PDF-'

if not is_pdf(file_bytes):
    raise ValueError('file is not a PDF')

Type guard

def is_pdf_bytes(data: bytes) -> bool:
    return isinstance(data, bytes) and data.startswith(b'%PDF-')

Try / catch

try:
    parser.parse(path)
except ValueError as e:
    if 'Failed to parse' not in str(e):
        raise
    logger.warning('skipping corrupt PDF %s: %s', path, e)

Prevention

When it happens

Trigger: Passing a non-PDF file (e.g. a .docx or HTML renamed to .pdf), a truncated download, or a password-protected/corrupt PDF.

Common situations: User uploads with wrong extension; interrupted downloads; encrypted PDFs; zero-byte files.

Understand the failure class

Related errors


AI-assisted analysis of agentscope-ai/agentscope@e90f1c7592 (2026-08-28). Data as JSON: /api/errors/7bd77a813189cb39. Report an issue: GitHub.