Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ One line per decision, with the reason, grouped by area in the order they were m
earlier ones; the first section lists what changed for the first public release. Add a line here when you change
the document format, a default, or a public interface.

## Haystack document conversion

- `ReadAnyDocConverter` uses the shared chunking helper so Haystack receives the same Markdown, split modes and
source metadata as the other adapters.

## Left-out values are warned by default (2026-11-20)

- `printed_but_empty` and `row_not_extracted` go into `warnings` on every extraction, not only with `review`:
Expand Down
33 changes: 26 additions & 7 deletions docs/guides/integrations.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
---
title: LangChain and LlamaIndex
description: Use ReadAnyDoc as a document loader in LangChain and a reader in LlamaIndex to load PDFs, scans and Office files as clean Markdown with page metadata for RAG.
title: LangChain, LlamaIndex and Haystack
description: Load PDFs, scans and Office files as Markdown with page metadata in LangChain, LlamaIndex and Haystack.
---

# LangChain and LlamaIndex
# LangChain, LlamaIndex and Haystack

ReadAnyDoc plugs into both frameworks as a loader. Each page becomes one document by default, as Markdown with tables
in HTML, and carries its page number, so answers can point back to the page.
Each page becomes one document by default, as Markdown with tables in HTML. The page number in the metadata lets
answers point back to the page.

## LangChain

Expand Down Expand Up @@ -36,6 +36,26 @@ docs = SimpleDirectoryReader("contracts/", file_extractor={".pdf": reader, ".doc
index = VectorStoreIndex.from_documents(docs)
```

## Haystack

```bash
pip install "readanydoc[engine,haystack]"
```

```python
from haystack import Pipeline
from readanydoc.integrations.haystack import ReadAnyDocConverter

pipeline = Pipeline()
pipeline.add_component("converter", ReadAnyDocConverter())
result = pipeline.run({"converter": {"sources": ["report.pdf", "appendix.docx"]}})
docs = result["converter"]["documents"]
print(docs[0].content, docs[0].meta)
```

Pass local file paths in `sources` and set `split` and parse options on the converter. If a source fails to parse,
the converter surfaces the error, as the other adapters do.

## Options

| Argument | Values |
Expand All @@ -44,5 +64,4 @@ index = VectorStoreIndex.from_documents(docs)
| any `readanydoc.parse` argument | `mode="model-only"`, `model=...`, `pages=[1, 2]`, ... |

The first document of a file carries `warnings` in its metadata when there are any (a page the provider declined,
an illegible value). Typed extraction with citations is not part of the loaders; call
[`readanydoc.extract`](extract.md) for that.
an illegible value). For typed extraction with citations, call [`readanydoc.extract`](extract.md).
2 changes: 1 addition & 1 deletion mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ nav:
- Async jobs and webhooks: guides/jobs-webhooks.md
- File types: guides/file-types.md
- Test it yourself: guides/testing.md
- LangChain and LlamaIndex: guides/integrations.md
- LangChain, LlamaIndex and Haystack: guides/integrations.md
- Use cases:
- Overview: use-cases/index.md
- Real documents, end to end: examples/real-documents.md
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,10 @@ Changelog = "https://github.com/arpitpatel25/ReadAnyDoc/blob/main/CHANGELOG.md"
engine = ["onnxruntime>=1.18", "numpy>=1.26", "rapidocr>=3.10"]
# kept for older install commands; the MCP server is part of the base install since 0.1.5
mcp = []
# document loaders for LangChain and LlamaIndex (readanydoc/integrations/)
# document adapters for LangChain, LlamaIndex and Haystack (readanydoc/integrations/)
langchain = ["langchain-core>=0.3"]
llamaindex = ["llama-index-core>=0.12"]
haystack = ["haystack-ai>=2.0"]

[project.scripts]
readanydoc = "readanydoc.cli:main"
Expand Down
1 change: 1 addition & 0 deletions readanydoc/integrations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from readanydoc.integrations.langchain import ReadAnyDocLoader # pip install "readanydoc[langchain]"
from readanydoc.integrations.llamaindex import ReadAnyDocReader # pip install "readanydoc[llamaindex]"
from readanydoc.integrations.haystack import ReadAnyDocConverter # pip install "readanydoc[haystack]"
"""

from __future__ import annotations
Expand Down
43 changes: 43 additions & 0 deletions readanydoc/integrations/haystack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Haystack document converter.

pip install "readanydoc[engine,haystack]"

from readanydoc.integrations.haystack import ReadAnyDocConverter
docs = ReadAnyDocConverter().run(sources=["report.pdf"])["documents"]
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, Union

try:
from haystack import Document, component, default_to_dict
except ImportError as e: # pragma: no cover
raise ImportError('The Haystack converter needs haystack-ai: pip install "readanydoc[haystack]"') from e

from . import chunks


@component
class ReadAnyDocConverter:
"""Converts local files to Markdown Documents, one per page by default.

``split``: "page" (default), "document" or "block". Other keyword arguments go to ``readanydoc.parse``.
"""

def __init__(self, split: str = "page", **parse_kwargs: Any):
self.split, self.parse_kwargs = split, parse_kwargs

def to_dict(self) -> dict[str, Any]:
"""Serialize parse options as constructor keywords for Haystack pipelines."""
return default_to_dict(self, split=self.split, **self.parse_kwargs)

@component.output_types(documents=list[Document])
def run(self, sources: list[Union[str, Path]]) -> dict[str, list[Document]]:
"""Convert the given file paths in order. Parser errors propagate to the caller."""
documents = []
for source in sources:
for text, metadata in chunks(source, self.split, **self.parse_kwargs):
documents.append(Document(content=text, meta=metadata))
return {"documents": documents}
52 changes: 51 additions & 1 deletion tests/test_integrations.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
"""LangChain and LlamaIndex adapters: chunking by page, block and document, metadata, no model calls."""
"""Framework adapters: chunking by page, block and document, metadata, no model calls."""
from pathlib import Path
from unittest.mock import Mock, call

import pytest

import readanydoc
Expand Down Expand Up @@ -44,3 +47,50 @@ def test_llamaindex_reader():
from readanydoc.integrations.llamaindex import ReadAnyDocReader
docs = ReadAnyDocReader(split="block").load_data("r.pdf", extra_info={"team": "finance"})
assert len(docs) == 3 and docs[0].metadata["team"] == "finance" and docs[0].text == "# Report"


@pytest.fixture
def haystack(monkeypatch):
monkeypatch.setenv("HAYSTACK_TELEMETRY_ENABLED", "false")
return pytest.importorskip("haystack")


def test_haystack_converter_pipeline(haystack, monkeypatch):
from readanydoc.integrations.haystack import ReadAnyDocConverter

parse = Mock(side_effect=fake_parse)
monkeypatch.setattr(readanydoc, "parse", parse)
sources = ["r.pdf", Path("s.pdf")]
pipeline = haystack.Pipeline()
pipeline.add_component("converter", ReadAnyDocConverter(mode="model-only"))
assert pipeline.to_dict()["components"]["converter"]["init_parameters"] == {
"split": "page", "mode": "model-only",
}
results = pipeline.run({"converter": {"sources": sources}})
docs = results["converter"]["documents"]

assert parse.call_args_list == [call(source, mode="model-only") for source in sources]
assert all(isinstance(doc, haystack.Document) for doc in docs)
assert [doc.content for doc in docs] == ["# Report\n\nRevenue grew.", "<table><tr><td>1</td></tr></table>"] * 2
assert [doc.meta for doc in docs] == [
{"source": "r.pdf", "page": 1, "warnings": ["page 2: check"]},
{"source": "r.pdf", "page": 2},
{"source": "s.pdf", "page": 1, "warnings": ["page 2: check"]},
{"source": "s.pdf", "page": 2},
]


@pytest.mark.parametrize("split", ["document", "block"])
def test_haystack_converter_split(haystack, split):
from readanydoc.integrations.haystack import ReadAnyDocConverter

docs = ReadAnyDocConverter(split=split).run(sources=["r.pdf"])["documents"]
assert [(doc.content, doc.meta) for doc in docs] == list(chunks("r.pdf", split))


def test_haystack_converter_surfaces_parse_errors(haystack, monkeypatch):
from readanydoc.integrations.haystack import ReadAnyDocConverter

monkeypatch.setattr(readanydoc, "parse", Mock(side_effect=FileNotFoundError("missing.pdf")))
with pytest.raises(FileNotFoundError, match="missing.pdf"):
ReadAnyDocConverter().run(sources=["missing.pdf"])
Loading