Skip to content

Techniques

This page lists the techniques Pagelore uses, what problem each one solves, and the option that controls it. Each section links to the page with the details.

Ingestion

Structure-aware extraction

Every loader returns the text as sections that keep their location: a PDF page, a slide, a sheet, a heading path, a subtitle's time range, the rows of a table. Chunks inherit the locations of the sections they cover, and the locations become citations such as report.pdf, pages 3-4, Refunds > Terms. → File types

Layout analysis with Docling

Docling runs layout models on each page: it puts multi-column text in reading order, rebuilds tables (including tables in PDFs) and runs OCR on scans. It runs locally with no LLM. Pagelore falls back to the native loader when Docling fails. → extractor: "docling", Docling

Running headers, footers and page numbers repeat on every page. Inside chunks they add noise to embeddings and break sentences in two. Pagelore removes lines repeated at the top or bottom of at least 30% of the pages before chunking, and records what it removed. → PDF_REMOVE_HEADERS_FOOTERS

OCR and transcription

Images and scanned PDFs go through Tesseract (--extra ocr). Audio and video are transcribed with local Whisper (faster-whisper) or OpenAI, and each chunk keeps its start_time / end_time. → OCR_LANGUAGES, TRANSCRIPTION_PROVIDER

Twelve chunking strategies

One size does not fit every format, so auto picks a strategy from the content type: table for spreadsheets, json for JSON, code for source files, markdown for Markdown, HTML and Word, page for slides, and recursive otherwise. → Chunking

Technique Strategy
Fixed windows with overlap, in characters or tiktoken tokens fixed, token
Recursive splitting: paragraphs, then sentences, lines and words, merged up to the size recursive
Whole-unit packing sentence, paragraph, page
Heading sections that keep the heading path markdown
Splits at class and function boundaries code
Semantic chunking: cut where the meaning shifts semantic
Row groups with the header repeated in every chunk table
Smaller valid JSON objects that keep each value's path json

Semantic chunking

Each sentence is embedded together with semantic_buffer_size neighbours on each side. The text is cut where the cosine distance between neighbouring sentences passes a threshold (Greg Kamradt's method). The threshold can be a percentile (default 95), a standard_deviation (3), an interquartile range (1.5) or a gradient percentile (95). Groups longer than chunk_size are split recursively. → strategy: "semantic"

Contextual chunk headers

A chunk such as "Revenue grew 4%" does not say which file, page or section it came from. With contextual_header, each chunk is embedded with a small block in front of it:

<document_metadata>
sourceDocument: report.pdf
title: ACME annual report 2024
page: 12
section: Results > Q3
</document_metadata>

Revenue grew 4% ...

The stored chunk text stays as it is, so results and citations are clean. → contextual_header, CHUNK_CONTEXTUAL_HEADER

Contextual retrieval

The same idea, written by an LLM: for each chunk, the configured LLM writes one to three sentences that place it in its document ("From ACME's 2024 annual report, the Q3 revenue section"). The context is embedded and keyword-indexed with the chunk, and stored apart from it (chunk_context). Pagelore keeps the cost down:

  • the document excerpt sits in a cached system prompt, so neighbouring chunks reuse it on providers with prompt caching;
  • several calls run at once (LLM_CONCURRENCY);
  • re-processing reuses the context of every chunk whose text has not changed;
  • long documents are sent as their start plus the part around each chunk, capped at LLM_CONTEXT_MAX_DOCUMENT_CHARS.

If the LLM fails, nothing is indexed with contexts missing. → llm_context, Chunking

Parent chunks

Consecutive chunks are grouped into larger parents, which end at section, sheet and table boundaries. The parents are not embedded; they are what small-to-big retrieval returns. → parent_chunk_size

Sources

Website crawling

Breadth-first crawling (nearest pages first) from one or more URLs, up to max_depth clicks and max_pages pages, on the same host by default, narrowed with include / exclude globs. XML sitemaps are read, robots.txt and robots meta tags are obeyed, and requests are spaced by URL_CRAWL_DELAY_MS or the site's Crawl-delay. → Text, web pages and S3

SSRF protection

A URL import is a request from your server, so an API user could point it at internal services. Pagelore resolves each host and refuses private, loopback and link-local addresses, also after every redirect, and connects only to the address it checked, so a DNS answer cannot change between the check and the connection (DNS rebinding). → URL_ALLOW_PRIVATE_NETWORKS

Conditional requests

A page imported before is requested with its ETag and Last-Modified. A 304 Not Modified answer means unchanged, with nothing downloaded. S3 objects are compared by their ETag in the same way. → POST /projects/{id}/sync

Server-side S3 credentials

S3 credentials come only from the server's settings (or boto3's default chain), never from requests, and S3_BUCKETS limits which buckets requests may read.

Storage and lifecycle

Postgres as the source of truth

Projects, documents, chunk text, metadata and the keyword index live in Postgres; the vector DB holds only vectors and a small payload. Results always take the text from Postgres, so a vector DB can be swapped or rebuilt without losing anything. → Architecture

Content hashing and versioning

Each file is hashed (SHA-256). The same content under the same key is a duplicate; other content becomes a new version. Old versions are deleted (rows, chunks, vectors and files) only after the new one is indexed, so search never has a gap and a failed upload never loses the old version. → on_conflict, Metadata and versions

Stale detection and reindexing

Each collection records the vector DB, embedding model, dimension and distance that created it, and each document records the collection it went into. After a configuration change, documents show stale: true, and one call rebuilds exactly what is needed. → Changing the model or vector DB

Migrations under an advisory lock

Alembic migrations hold a Postgres advisory lock, so replicas that start at the same time migrate once instead of racing. → Database migrations

Retrieval

The query is embedded with the collection's model (with EMBEDDING_QUERY_PREFIX for models such as E5, BGE and nomic) and searched in the vector DB. Every vector carries an indexed project_id and document_id, so the search is limited to the right project, and to the documents a filter allows, inside the vector DB itself. → mode: "vector"

BM25 keyword search in Postgres

Every chunk gets a Postgres full-text vector (tsvector, GIN index), stemmed for the project's language. Postgres' own ts_rank has no document frequency, so Pagelore computes Okapi BM25 in SQL (k1 1.2, b 0.75): rare words weigh more, and repeats in a long chunk weigh less. Matching can be any word, or all with web search syntax ("phrases", -word, or). → mode: "keyword", Hybrid search

Hybrid search and fusion

Both searches run and their lists are fused:

  • Reciprocal rank fusion (RRF): each list adds weight / (rrf_k + rank), with rrf_k 60. It uses ranks only, so the score scales do not matter.
  • Relative score fusion: each list's scores are scaled to 0-1 (min-max), then added with the weights.

alpha weighs the vector list, and the keyword list gets 1 - alpha. → mode: "hybrid", fusion, alpha, rrf_k

Small-to-big retrieval

Small chunks match precisely, but are often too short to answer from. The small chunks are searched, chunks of the same parent are merged into one result scored by its best chunk, and the parent passage is returned. → return_parents, Small-to-big

Cross-encoder reranking

A cross-encoder reads the query and each candidate together, which is more accurate than comparing embeddings, but slower. So retrieval finds a short list (by default 4 x top_k, at least 20, at most 100) and the reranker puts it in order. Thirteen providers, local or hosted. → rerank, Reranking

Query transformations

The LLM rewrites the question before searching, in one call: a standalone rewrite of a chat follow-up, multi-query phrasings, HyDE hypothetical answers (searched by vector), decomposition into sub-questions, a step-back question, and keyword expansion (searched by keyword). Each query is searched and the lists are fused with RRF. → query_transform, Query transformations

Knowledge graph (HippoRAG-style)

Entities and relations are extracted from every chunk (by the LLM, or by free rules), and entities with the same name are merged across documents. At query time a Personalized PageRank walk starts from the entities the query names and the search's best chunks, and the chunks it reaches are fused into the results with RRF. It finds passages linked to the question through a shared entity, not shared words. → graph, Knowledge graph

Maximal marginal relevance (MMR)

Top results are often near-copies of each other. MMR picks results one by one, each time taking the one that maximises

λ · relevance − (1 − λ) · max similarity to the results already picked

with λ = 1 − diversity. Similarity is the cosine of the stored vectors in the vector mode, and word overlap (Jaccard) in the keyword and hybrid modes. After reranking, the reranker's scores are the relevance. → diversity

De-duplication, per-document caps and neighbours

  • dedupe drops results whose text (ignoring case and spacing) repeats a better one.
  • max_per_document stops one long document from filling the results.
  • neighbors adds the chunks around each result as context, merged without repeating the overlaps.

Filters

A MongoDB-style metadata filter language ($eq, $ne, $in, $nin, $gt, $gte, $lt, $lte, $exists, $and, $or, $not), plus filters on source, external id, document id, file extension, upload date and page range. Document-level filters are resolved in Postgres into a set of document ids, which the vector search and the keyword search are limited to (up to 1000 ids; beyond that, and for page filters, results are filtered afterwards and more candidates are fetched). → Retrieval

Evaluation

Synthetic test questions

The LLM samples chunks spread across the documents and writes, for each one, a question it answers in other words than the chunk uses (so keyword overlap does not make the test easy). The answer is recorded as a character range of the document, so questions stay valid after re-chunking. → Evaluation

Information-retrieval metrics

Hit rate, MRR, nDCG, recall and precision at top_k, plus latency, for any number of retrieval configs on the same questions. A result counts as relevant when it overlaps the answer range by at least half of the shorter of the two.

Word-based quote matching

A question can be pinned to a quote the result must contain. Quotes compare words only, ignoring case, spacing, punctuation and Markdown, so the check works the same on native text and on Docling's Markdown. → Native or Docling?

LLM calls

Structured output with one repair retry

Internal features ask the LLM for JSON and enforce it in the strongest way the provider supports: a JSON schema the API constrains the reply to, JSON mode, or prompt instructions only. Every reply is parsed and validated; reasoning sections (<think>...</think>) are removed, and an invalid reply is sent back once with the error. → LLM_STRUCTURED_OUTPUT, LLM