Skip to main content

A minimal, extensible framework for preparing documents for RAG/LLM workflows

Project description

rag_prep

A minimal, extensible framework for preparing documents for RAG/LLM workflows.

Pipeline: load → normalize → chunk → emit

Design Philosophy

  • Simple, orthogonal building blocks - Each component has a clear, single responsibility
  • Clear interfaces for extensibility - Protocols and ABCs make it easy to plug in custom implementations
  • Sensible defaults with freedom to override - Works out of the box, but nothing is hardcoded
  • Python API first - CLI is a thin wrapper over the Python API

Installation

pip install rag-prep

For optional file format support:

# PDF support
pip install rag-prep[pdf]

# DOCX support
pip install rag-prep[docx]

# HTML support
pip install rag-prep[html]

# All optional dependencies
pip install rag-prep[all]

Quick Start

Python API

from rag_prep import prepare_docs, prepare_docs_to_jsonl, Config

# Simple usage with defaults
prepare_docs_to_jsonl("document.txt", "output.jsonl")

# With custom configuration
config = Config(
    chunk_strategy="token",
    chunk_size=500,
    chunk_overlap=100,
    tokenizer_name="cl100k_base",
)

prepare_docs_to_jsonl("document.txt", "output.jsonl", config=config)

# Get chunks as iterator (for custom processing)
from rag_prep import prepare_docs

for chunk in prepare_docs("document.txt", config=config):
    print(chunk.text)
    print(chunk.metadata)

CLI

# Basic usage
rag-prep document.txt -o output.jsonl

# With custom chunking
rag-prep document.txt -o output.jsonl \
    --chunk-strategy token \
    --chunk-size 500 \
    --chunk-overlap 100

# Process directory with filters
rag-prep ./documents -o output.jsonl \
    --include "*.txt" "*.md" \
    --exclude "*.tmp" \
    --chunk-strategy sentence

# Verbose output
rag-prep document.txt -o output.jsonl -v

Extension Points

1. Custom Chunking Strategies

Create a custom chunker by implementing the ChunkingStrategy protocol:

from typing import Iterator
from rag_prep.models import Chunk
from rag_prep.chunkers import ChunkingStrategy

class MyCustomChunker:
    def __init__(self, size: int = 1000, overlap: int = 200):
        self.size = size
        self.overlap = overlap
    
    def chunk(self, text: str, metadata: dict) -> Iterator[Chunk]:
        # Your custom chunking logic
        # ...
        yield Chunk(text=chunk_text, metadata=chunk_metadata)

Use it in Python:

from rag_prep import prepare_docs, Config

config = Config(chunk_strategy="character")  # Will use your chunker if registered
chunker = MyCustomChunker(size=500)
chunks = prepare_docs("doc.txt", config=config, chunker=chunker)

Or via CLI with module path:

rag-prep doc.txt -o out.jsonl --chunk-strategy mypackage.MyCustomChunker

2. Custom Loaders

Register a loader for a new file type:

from rag_prep.loaders import Loader, register_loader, TextLoader

class JSONLoader:
    def load(self, source):
        import json
        with open(source, 'r') as f:
            data = json.load(f)
            # Convert to Chunk objects
            yield Chunk(text=str(data), metadata={"source": source})

# Register for .json files
register_loader(".json", JSONLoader())

3. Custom Output Sinks

Implement the Sink protocol:

from rag_prep.sinks import Sink
from rag_prep.models import Chunk
from typing import Iterator

class DatabaseSink:
    def write(self, chunks: Iterator[Chunk]):
        # Write chunks to your database
        for chunk in chunks:
            # ... insert into database
            pass

4. Metadata Enrichment

Add metadata hooks to enrich chunks:

from rag_prep import Config, prepare_docs

def add_timestamp(metadata, text):
    import datetime
    metadata["processed_at"] = datetime.datetime.now().isoformat()
    return metadata

config = Config(metadata_hooks=[add_timestamp])
chunks = prepare_docs("doc.txt", config=config)

5. Custom Tokenizers

Inject your own tokenizer:

from rag_prep import prepare_docs, Config
from rag_prep.tokenizers import Tokenizer

class MyTokenizer:
    def encode(self, text: str) -> list:
        # Your encoding logic
        return tokens
    
    def decode(self, tokens: list) -> str:
        # Your decoding logic
        return text

tokenizer = MyTokenizer()
config = Config(chunk_strategy="token")
chunks = prepare_docs("doc.txt", config=config, tokenizer=tokenizer)

Built-in Features

Chunking Strategies

  • character - Character-based chunking (default)
  • token - Token-based chunking (requires tokenizer)
  • sentence - Sentence-aware chunking
  • none - No chunking (entire document as single chunk)

Supported File Types

  • .txt - Plain text
  • .md, .markdown - Markdown
  • .pdf - PDF (requires rag-prep[pdf])
  • .docx - Word documents (requires rag-prep[docx])
  • .html, .htm - HTML (requires rag-prep[html])
  • .csv - CSV files (each row becomes a document)

Output Format

Default output is JSONL (JSON Lines), where each line is a chunk:

{"text": "chunk text...", "metadata": {"source_id": "doc.txt", "chunk_index": 0}, "chunk_id": "doc.txt_chunk_0"}
{"text": "next chunk...", "metadata": {"source_id": "doc.txt", "chunk_index": 1}, "chunk_id": "doc.txt_chunk_1"}

Architecture

rag_prep/
├── models.py      # Chunk, Config data models
├── chunkers.py    # Chunking strategies (Protocol + implementations)
├── loaders.py     # Document loaders (registry pattern)
├── sinks.py       # Output sinks (Protocol + implementations)
├── tokenizers.py  # Tokenization backend (Protocol + tiktoken)
├── pipeline.py    # Main prepare_docs() API
└── cli.py         # Command-line interface

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rag_prep-0.1.1.tar.gz (21.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rag_prep-0.1.1-py3-none-any.whl (14.1 kB view details)

Uploaded Python 3

File details

Details for the file rag_prep-0.1.1.tar.gz.

File metadata

  • Download URL: rag_prep-0.1.1.tar.gz
  • Upload date:
  • Size: 21.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for rag_prep-0.1.1.tar.gz
Algorithm Hash digest
SHA256 94e7f713578dfe1a9cffa6c1f45ef154e7d2f55ffde36ce7d7883d65bbb14e4c
MD5 2262d888e278ac03f4f1501a7bf66845
BLAKE2b-256 f35c53ec49be3a683aac2514a53efdb5e7672e486e29af1adf0298f418d8a736

See more details on using hashes here.

File details

Details for the file rag_prep-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: rag_prep-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 14.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for rag_prep-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 41c995a9142ebe028903f38e8f486895e30b5500360534dfe4c1dd887e882916
MD5 4d78bd7b94c5cf5f871d22fbf84a7d23
BLAKE2b-256 8f04c1f3a85e811f9c71ccb497967f3aeedc5552e528d6b5690c656501852d61

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page