Skip to main content

Office-document RAG

PyPI Python License: MIT

Retrieval-augmented Q&A over PDF, DOCX, PPTX and XLSX files, built from:

Stage Library Role
Parse Docling Converts PDF and Office files into a structured document: headings, paragraphs, lists, tables, images, speaker notes, sheets, pages
Chunk Chonkie RecursiveChunker for prose, TableChunker for large tables (header repeated in every chunk)
Index + query RAG-Anything (on LightRAG) Multimodal knowledge graph + vector index; tables and images are analysed by the LLM / vision model
Models Claude (claude-opus-5-5, on the Claude API, Bedrock, Vertex AI or Foundry) + local sentence-transformers embeddings and optional reranker LLM, vision, embeddings, reranking

Architecture

A rendered copy is at docs/architecture.png, for editors that don't render Mermaid.

flowchart TB
    subgraph SRC["Sources"]
        F["PDF / DOCX / PPTX / XLSX<br/>any European language"]
    end

    subgraph PARSE["1 · Parse — Docling"]
        DC["DocumentConverter"] --> DD["DoclingDocument<br/>reading order · BODY + NOTES layers"]
        DD --> W["Walker + normalize_text<br/>NFC · soft hyphens · no-break spaces"]
    end

    subgraph CHUNK["2 · Chunk — Chonkie"]
        RC["RecursiveChunker<br/>EUROPEAN_RULES"]
        TC["TableChunker<br/>row windows, header repeated"]
    end

    subgraph CL["3 · Content list — MinerU format"]
        TXT["text chunks<br/>breadcrumb + chunk separator"]
        TAB["table items"]
        IMG["image items<br/>PNG on disk"]
        EQ["equation items"]
    end

    subgraph RA["4 · Index — RAG-Anything + LightRAG"]
        LR["LightRAG text insert<br/>split only at chunk separators"]
        MP["Modal processors<br/>table · image · equation"]
        EX["Entity + relation extraction<br/>written in KG_LANGUAGE"]
    end

    subgraph MODELS["Models"]
        CL4["Claude claude-opus-5-5<br/>LLM + vision"]
        EMB["bge-m3<br/>local multilingual embeddings"]
    end

    subgraph STORE["5 · Storage — rag_storage/"]
        KV[("KV: docs · chunks · status")]
        VDB[("Vectors: chunks · entities · relations")]
        KG[("Knowledge graph")]
    end

    subgraph Q["6 · Query"]
        QU["Question, any language"] --> KW["Keyword extraction"]
        KW --> RET["Retrieve: vector search + graph traversal<br/>mode mix · hybrid · local · global · naive"]
        RET --> ANS["Answer in the question's language"]
    end

    F --> DC
    W -- "prose · lists · speaker notes" --> RC --> TXT
    W -- "table > 40 rows" --> TC --> TXT
    W -- "table ≤ 40 rows, or 20-row preview" --> TAB
    W -- pictures --> IMG
    W -- formulas --> EQ

    TXT --> LR --> EX
    TAB --> MP
    IMG --> MP
    EQ --> MP
    MP --> EX

    EX -. calls .-> CL4
    MP -. calls .-> CL4
    LR -. embeds .-> EMB

    LR --> KV
    LR --> VDB
    EX --> VDB
    EX --> KG

    KW -. calls .-> CL4
    RET --> VDB
    RET --> KG
    RET --> KV
    RET -. embeds .-> EMB
    ANS -. calls .-> CL4

Each Chonkie chunk ends with a ␞ separator, and LightRAG is told to split only on it, so LightRAG keeps Chonkie's chunk boundaries instead of re-chunking. Documents get IDs from a hash of their contents, so re-ingesting an unchanged file is a no-op. A manifest (rag_storage/brag_manifest.json) records which file holds which document, so an edited file replaces its old version instead of sitting next to it.

Installation

pip install brag-rag        # or: uv tool install brag-rag

The package is published on PyPI as brag-rag. This installs the brag command and the brag Python package. Then put your API key in the environment, or in a .env file in the directory you run brag from (see .env.example):

export ANTHROPIC_API_KEY=sk-ant-...

The embedding model (BAAI/bge-m3 by default, about 2.3 GB) downloads on first use. Switching it later means deleting rag_storage/ and re-ingesting, because vector dimensions change.

From source

uv sync
cp .env.example .env   # then set ANTHROPIC_API_KEY
uv run brag --help

Usage

brag parse samples/sales.xlsx          # preview chunks; no API calls
brag ontology propose samples/         # optional: entity types for this corpus
brag ingest samples/ ~/Docs/q3.pptx    # files and/or folders (recursive)
brag query "Which region grew fastest?"
brag query "Summarise the Widget Pro launch" --mode hybrid
brag chat

Query modes: mix (graph + vector, default), hybrid, local, global, naive (vector only). Answers end with a References section listing the files and the slides, sheets or pages each fact came from.

Keeping the index in sync

brag ingest samples/            # re-run any time: new files are added, edited ones replaced
brag list                       # what is indexed, and which files no longer exist
brag remove samples/old.pptx    # drop a file, or every file under a folder

brag ingest prints one line per file (indexed, updated, unchanged, empty or failed), the token usage, and exits with status 1 if any file failed, so it can run in scripts and CI. Files are named in the index by their path relative to where you run brag, so run it from the same folder each time.

Indexes built with brag 0.1 have no manifest. Their unchanged files are picked up on the next ingest; for files edited since, start over (rm -rf rag_storage output, then ingest).

Entity types (ontology)

LightRAG tags entities with generic types (person, organization, location, event, concept, …). For a specific corpus, types such as Product, SalesRegion or FinancialMetric give a more useful graph:

brag ontology propose samples/   # samples the files, asks Claude, writes ontology.yaml

Review and edit ontology.yaml. Only the type names are used for extraction; descriptions and examples are there to help you decide. Re-running propose on new documents only adds types, so your edits stay. To keep a type you deleted from coming back, list it under rejected. When ontology.yaml exists, brag ingest uses it. Changing types after ingesting only affects documents indexed afterwards, so re-index for a consistent graph; brag warns when the types differ from the ones the index was built with.

The approach (an LLM proposes a schema from samples of the data, a person reviews it, re-runs keep edits) follows NVIDIA auto-ontology, which does this for relational databases.

The index is stored in ./rag_storage and parsed images in ./output, relative to the current directory (set WORKING_DIR / OUTPUT_DIR to change this).

From Python:

from dotenv import load_dotenv
from brag import RAGPipeline

load_dotenv()  # optional: the library reads settings from the environment only

pipeline = RAGPipeline()
for result in await pipeline.ingest(["docs/"]):
    print(result.source, result.status, result.error)
answer = await pipeline.query("What is the Q4 outlook?")
await pipeline.remove(["docs/old.pptx"])
await pipeline.close()

Evaluation

brag eval scores the index against a golden set of questions, so changes such as a reranker, another chunk size or a different backend can be compared with numbers instead of impressions.

brag ingest samples/
brag eval eval/samples.yaml                       # retrieval only
brag eval eval/samples.yaml --answers --output report.json
brag eval eval/samples.yaml --min-recall 0.9      # exit 1 below the threshold (for CI)
Metric What it measures Cost
recall@k Share of a question's expected sources found in the top k chunks None in naive mode; one keyword call per question in graph modes
hit@k Whether any expected source is in the top k as above
MRR 1 / rank of the first chunk from an expected source as above
facts Share of expected facts that appear in the answer (--answers) One answer per question
groundedness Share of the answer's claims the retrieved context supports, judged by Claude (--answers) One judge call per question

A golden file lists questions, the files (optionally a slide, sheet or page) each should be answered from, and facts the answer must contain; see eval/samples.yaml and the docstring of brag.evaluation. Write one for your own documents: a few dozen real questions tell you far more than the samples. The report records the configuration (mode, k, models, backends) next to the scores, so runs can be compared.

The Evaluation workflow runs the sample set in GitHub Actions on demand; it needs an ANTHROPIC_API_KEY repository secret.

Multilingual documents

Documents in any European language (Latin, Greek and Cyrillic scripts, plus Armenian and Georgian) can be mixed in one index. No language detection or per-language setup is needed.

  • Normalisation (multilingual.normalize_text): applies Unicode NFC, so decomposed accents such as u + ¨ become ü. It strips soft hyphens and zero-width characters, and turns no-break spaces (including French narrow ones before ? and !) into normal spaces. NFC also folds the Greek question mark into ;.
  • Chunk boundaries (multilingual.EUROPEAN_RULES): splits at paragraphs, then sentences, then clauses, then words, then characters. Sentence ends include . ! ? … ; and the Armenian ։, and also count when followed by a closing quote (" ” “ » « ’). Unlike Chonkie's defaults, the rules never split on ' or -, which would break French and Italian elisions (l'homme, dell'anno) and hyphenated compounds.
  • Embeddings: bge-m3 places all languages in one vector space, so an English question retrieves German, French, Greek or Polish passages.
  • Knowledge graph: entities and descriptions are written in one canonical language (KG_LANGUAGE, English by default). That way "Europäische Union" and "Union européenne" merge into a single entity. Proper nouns stay in their original language.
  • Answers come back in the language of the question.

Configuration

All settings are environment variables; see .env.example. The main ones:

  • LLM_PROVIDER: where Claude runs: anthropic (the Claude API, default), bedrock, vertex or foundry, for data-residency rules. Each uses its platform's usual credentials (.env.example lists them). On Vertex, install brag-rag[vertex]. Model IDs differ by platform: Bedrock defaults to anthropic.claude-opus-5-5; on Foundry set LLM_MODEL to your deployment name.
  • LLM_MODEL, LLM_EFFORT: the Claude model and effort used for ingestion (entity extraction, table and image analysis) and for answers. Ingestion makes several LLM calls per chunk, so for large corpora a lower effort or a cheaper model is the main cost lever.
  • RERANK_MODEL: a local cross-encoder that re-scores retrieved chunks before they reach Claude. BAAI/bge-reranker-v2-m3 is multilingual (about 2.3 GB). Off by default; measure it with brag eval before keeping it.
  • KV_STORAGE, VECTOR_STORAGE, GRAPH_STORAGE, DOC_STATUS_STORAGE: LightRAG storage backends, for example PGKVStorage, PGVectorStorage, Neo4JStorage or QdrantVectorDBStorage, configured with LightRAG's own variables (POSTGRES_HOST, NEO4J_URI, ...). Install the driver with an extra: brag-rag[postgres], [neo4j], [qdrant], [milvus], [mongo] or [redis]. WORKSPACE keeps several indexes apart in one set of backends. brag's file manifest (rag_storage/brag_manifest.json) and extracted images stay on local disk, so run ingestion from one machine.
  • PDF_OCR: OCR for scanned PDFs (off by default; needs an OCR engine that Docling supports, such as rapidocr-onnxruntime). Text-based PDFs work without it. Borderless tables in PDFs may be read as plain text.
  • CHUNK_SIZE: Chonkie chunk size in o200k_base tokens. LightRAG's limit is set 256 tokens higher to leave room for the breadcrumb.
  • TABLE_MODAL_MAX_ROWS: the cutoff between analysing a table as one unit and row-chunking it.
  • KG_LANGUAGE: the language the knowledge graph is written in. Changing it after ingestion mixes languages in the graph, so re-index if you change it.
  • ONTOLOGY_FILE: where entity types are read from (default ./ontology.yaml). Without the file, ENTITY_TYPES (a JSON list) or LightRAG's defaults apply.

Entity extraction sends the same long instructions with every chunk, so the system prompt is sent with prompt caching: after the first chunk it is read from cache at a fraction of the input price. brag ingest reports how much input was served from cache.

If a safety classifier declines a request, it is retried on a fallback model: on the Claude API through the server-side fallbacks parameter (the server picks the model unless LLM_FALLBACK_MODEL is set), on Bedrock, Vertex and Foundry through the SDK's client-side fallback middleware (default fallback claude-opus-4-8).

Layout

src/brag/cli.py           `brag` command
src/brag/config.py        settings
src/brag/parsing.py       Docling → Chonkie → RAG-Anything content list
src/brag/multilingual.py  Unicode normalisation + European chunking rules
src/brag/models.py        Claude LLM/vision (prompt caching, token usage) + local embeddings
src/brag/pipeline.py      LightRAG + RAG-Anything wiring: ingest, update, remove, query
src/brag/manifest.py      which file is indexed under which document ID
src/brag/ontology.py      entity-type proposal and ontology.yaml
src/brag/evaluation.py    golden-set evaluation (recall@k, MRR, facts, groundedness)
eval/samples.yaml         golden questions for samples/
tests/                    pytest suite; no API key needed (the PDF test downloads Docling's layout model once)
samples/                  example files in English, German, French, Greek and Polish

Development

uv sync
uv run pytest

Releasing

  1. Bump __version__ in src/brag/__init__.py.
  2. Optional dry run: run the Publish workflow by hand from the Actions tab; it uploads to TestPyPI. TestPyPI rejects re-uploads of the same version, so bump the version before each dry run.
  3. Create a GitHub release tagged v<version> (e.g. v0.2.0).
  4. The publish workflow builds the sdist and wheel and uploads them to PyPI with trusted publishing.

To publish by hand instead: uv build && uv publish (needs a PyPI API token).

License

MIT

Metadata

Release files for brag-rag 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for brag-rag 0.3.0
File Size Uploaded Provenance Actions
brag_rag-0.3.0.tar.gz 32.5 kB With provenance Details for brag_rag-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for brag-rag 0.3.0
File Interpreter ABI Platform Actions
brag_rag-0.3.0-py3-none-any.whl Python 3 none any Details for brag_rag-0.3.0-py3-none-any.whl

Total release size: 69.9 kB

Release files / brag_rag-0.3.0.tar.gz

Download URL brag_rag-0.3.0.tar.gz
Size 32.5 kB
Tags Source
SHA-256 checksum
How to use checksums
cdf035c598395c9ba8a9d8c0e53b40babb27bed56c3d174344acb41a2cd56a2a
BLAKE2b-256 checksum
How to use checksums
5df2e706486eb1d88f2ea65e4120991201af6766638fbd76fc003d877392b506
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / brag_rag-0.3.0-py3-none-any.whl

Download URL brag_rag-0.3.0-py3-none-any.whl
Size 37.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a1844fb31b4315c898af6cd12e896fa23f87629dc697c44de991e57368231a4a
BLAKE2b-256 checksum
How to use checksums
73166691d1758f4e3d9286aae37b67b6f2c040828f228423c0280ecbfabe245a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for brag-rag 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for brag_rag-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page