What it does
- Hybrid search: in-house BM25 plus a vector index
- Filters and result diversification
- Context assembly with citations
- Stays within the token budget
Measured
- BM25 on 1 million chunks: 1.57 ms at p50 (GCC), 1.73 ms (MSVC), with the same top k as the exhaustive search
- Hybrid search on 1 million chunks: 7.4 to 8.5 ms
- Quality on NFCorpus: hybrid nDCG@10 of 0.352
- BM25 scores match rank_bm25, and the stemmers match snowballstemmer on 100% of the words
Known limits
- Opening a snapshot reads it whole into memory (no memory-mapped load)
- Compaction is not automatic, and many small upserts weaken BM25 until Compact runs
- CJK text is not segmented into words. Sentence splitting and stopwords cover English, Portuguese and Spanish, and stemming covers English and Portuguese
Ethereal::Ai::Rag · off by default
Retrieval augmented generation over documents on the local machine. The module loads documents (text, Markdown, HTML, CSV, JSONL, source code), splits them into chunks, indexes each chunk twice (BM25 for the words and a vector index for the meaning), answers dense, sparse or hybrid queries with metadata filters, MMR and deduplication, and packs the best passages into a token budget with citation markers, ready for a language model. The index saves to disk as an atomic snapshot and compacts while queries run.
It runs fully offline with a local model of [Ai::Embed](ai-embed.md), or with the embeddings endpoint of a remote provider through [Ai::Llm](ai-llm.md). With no provider at all, the index is sparse only (BM25).
The module is optional: -DETHEREAL_AI_RAG=ON, which requires ETHEREAL_AI_EMBED (and therefore ETHEREAL_AI_TOKENIZER), ETHEREAL_VECTORINDEX and ETHEREAL_TEXT_NORMALIZATION. CMake stops with the reason when one is missing. ETHEREAL_AI_LLM is optional: without it, the remote provider, the model reranker and AddContextToRequest return eUnsupported.
#include <ethereal/cpp/ai/embed/embed_inc.hpp>
#include <ethereal/cpp/ai/rag/rag_inc.hpp>
namespace Rag = Ethereal::Ai::Rag;
namespace Embed = Ethereal::Ai::Embed;
Embed::CModel Model;
Embed::CModel::LoadSafetensors( "models/e5-small-v2", {}, &Model );
Rag::CLocalEmbedding Embedder( Model, "query: ", "passage: " );
Rag::SIndexConfig Config;
Config.sCachePath = "rag/embeddings.db";
Rag::CIndex Index;
Rag::CIndex::Create( Config, &Embedder, &Index );
std::vector< Rag::SDocument > Docs;
Rag::LoadFile( "manual.md", {}, Docs );
Index.Upsert( Docs.data(), Docs.size() );
Rag::CQuerySession Session; // one per thread
Rag::SQuery Q;
Q.sText = "how do I reset the password?";
Rag::SQueryResult Result;
Index.Query( Q, Session, Result );
Rag::SContext Context;
Index.BuildContext( Result, 1500, Session, Context ); // Context.sText goes to the model, with [1], [2]...
Index.Save( "rag/snapshot" );The model is not part of the SDK. You supply it, as for Ai::Embed.
The example
examples/ai/semantic_search_offline.cpp indexes a folder and answers queries in the terminal:
semantic_search_offline <model folder or .etlemb> <folder> [--index <dir>] [--e5]It loads the model in int8, indexes every file the loaders read under the folder (hidden folders skipped), and prints the hits with their BM25 and cosine scores. With --index, the snapshot and the embedding cache live there: the next run opens the snapshot and embeds only new or changed text. --e5 adds the e5 prefixes. A query that starts with ? prints the context a model would receive. An empty line quits.
---
Documents and loaders
An SDocument is a stable id chosen by you, the text (or a PFN_LoadText callback that loads it only when it is indexed), and metadata (SMeta: a key and an SMetaValue of type string, integer, real, bool or date, a date being days since 1970-01-01).
| Piece | What it does |
|---|---|
LoadFile( path, Options, Out ) | the documents of a file, the kind from the extension |
LoadDocuments( sourceId, bytes, eKind, Options, Out ) | the same from memory. Out is replaced on success and untouched on error |
KindFromPath( path ) | .md, .html/.htm, .csv, .jsonl/.ndjson, common source code extensions, anything else is text |
DecodeToUtf8( bytes, Out ) | UTF-8 with or without BOM, or UTF-16 with BOM (LE or BE). Anything else is eEncodingError |
HtmlToText( html, Out ) | tags removed, entities decoded, script and style dropped, block tags as line breaks |
SplitSentences( text, eLanguage, Out ) | sentence spans (see below) |
Text, Markdown, code and HTML give one document per file. CSV gives one per row (header row first) and JSONL one per line. SLoaderOptions names the text field (sTextField, default text) and the id field (sIdField, default id, the row number when absent), the CSV separator, and a size limit (uMaxBytes, 256 MiB). The other scalar fields become metadata (strings, for CSV). PDF, Office documents and other binary formats are not read.
The sentence splitter (English, Portuguese, Spanish) ends a sentence at ., !, ? or … followed by a space and a capital, a digit or opening punctuation, or at a blank line. It does not split at abbreviations of the language, initials, numbers (3.14, 1.000,50), an ellipsis inside a sentence, or a dot inside a URL or an e-mail address.
---
Chunking
ChunkText( text, Config, Counter, Out ), or automatically inside the index. No chunk exceeds the budget (except a single token longer than it), no cut falls inside a code point, and without overlap the chunks tile the text exactly.
EChunker | How it cuts |
|---|---|
eFixedTokens | windows of uMaxTokens, each starting uMaxTokens - uOverlapTokens after the last |
eRecursive (default) | paragraphs, then sentences, then words, merged up to the budget |
eMarkdown | the section of each heading, chunked recursively, with the heading path in sHeadingPath |
eCode | function and block boundaries by braces and indentation, merged up to the budget |
SChunkConfig defaults: eRecursive, 256 tokens, overlap 32 (fixed windows only), English. Tokens are counted by an ITokenCounter: CWordCounter (words, the default) or CTokenizerCounter (the tokens of an Ai::Tokenizer model, so the budgets match what the model sees).
---
Analysis and BM25
CAnalyzer turns text into terms: NFKC, lowercase, accents removed (optional), words by Unicode letters and digits, stopwords dropped and words stemmed (optional). SAnalyzerConfig sets the language (ELanguage: none, English, Portuguese, Spanish). Stemming exists for English (Snowball Porter2, as revised in Snowball 3) and Portuguese (Snowball). Spanish has stopwords but no stemmer. StemEnglish, StemPortuguese and IsStopword are public.
CBm25Index is usable on its own: Add the analyzed documents, Finalize, then Search from any number of threads. Postings go in blocks of 128 documents with the best score each block can reach, and search runs Block-Max WAND. It returns exactly the top k of the exhaustive search, scores included (SearchExhaustive is there for comparison). Ties go to the lower document number. SBm25Config: fK1 1.2, fB 0.75, and the idf (EIdf::eLucene, never negative, the default, or eOkapi, that of rank_bm25's BM25Okapi). Serialize and Deserialize save and restore it.
---
Embedding providers
| Piece | What it does |
|---|---|
IEmbeddingProvider | the interface: ModelId, Dimensions, EmbedPassages, EmbedQuery. Must be thread safe and return normalized vectors |
CLocalEmbedding( Model, queryPrefix, passagePrefix, modelId ) | an Ai::Embed model, offline. Keeps one session per calling thread, so warm calls do not allocate |
CRemoteEmbedding( Client, model, dimensions, queryPrefix, passagePrefix ) | the embeddings endpoint of OpenAI and compatible servers, through Ai::Llm. Vectors normalized here |
CEmbeddingCache | vectors keyed by the SHA-256 of the model id and the text, in a Storage database (crash safe, one writer, many readers). Hits() and Misses() count |
With SIndexConfig::sCachePath set, reingesting a document whose chunks did not change computes no embedding. Changing the model changes every key. An empty model id in CLocalEmbedding is derived from the model's description.
---
The index
| Piece | What it does |
|---|---|
CIndex::Create( Config, pEmbedder, &Index ) | an empty index. A null provider gives a sparse only index |
CIndex::Open( dir, Config, pEmbedder, &Index ) | a saved snapshot. The same chunking and analysis, and a provider with the same model and dimensions, are required |
Upsert( pDocs, uCount ) | adds documents, replacing those with the same id. A query sees all of them or none |
Remove( docId ) | eNotFound when absent |
Query( Q, Session, Out ) | dense, sparse or hybrid search |
BuildContext( Result, uTokenBudget, Session, Out ) | the passages of a result within a token budget |
Save( dir ) / Compact() | snapshot, and the removed chunks dropped |
Documents(), Chunks(), Segments(), Config(), DocumentText( id, Out ), Cache() | state and text |
SIndexConfig: Chunking, Analyzer, Bm25, uCapacity (chunks of the vector index, allocated up front, 100,000), uM (16) and uEfConstruction (200) of the graph, sCachePath, pCounter, pReranker (an IReranker, for example CLlmReranker, which asks a model of Ai::Llm to score the passages from 0 to 10), pParallel (threads for chunking and analysis at ingestion), uEmbedBatch (32 texts per provider call) and fPrefilterBelow (0.05).
Queries
SQuery field | Default | What it does |
|---|---|---|
eMode | eHybrid | eDense, eSparse or eHybrid. Dense and hybrid need a provider (eUnsupported otherwise) |
uTopK, uCandidates | 10, 50 | size of the result, and of each list before fusion, reranker, MMR and dedup |
eFusion, fRrfK, fDenseWeight | RRF, 60, 0.5 | reciprocal rank fusion, or weighted fusion of min-max normalized scores |
pFilters, uFilters | none | conditions on metadata, all must hold (eEqual, eRange both ends included, eIn) |
fMmrLambda | 1 (off) | below 1 trades relevance for diversity |
fDedupCosine | 1 (off) | below 1 drops a chunk this close to one already taken |
eDenseSearch, uEf | eAuto, 64 | automatic, exact, or graph search, and the graph search width |
bRerank | false | runs the index's reranker on the candidates |
When the filters pass fewer than fPrefilterBelow of the chunks, they run before the search (a bitmap), otherwise after it, with a fallback to before when too few pass. SQueryResult::bPrefiltered says which. Each SHit has the chunk id, the document id, the byte range of the chunk in the document's text, the final score, the BM25 score, the cosine and the rank in each list (-1 when absent). The views of a result live until the next Query or BuildContext with the same session.
Context
BuildContext takes the hits best first, merges adjacent or overlapping chunks of the same document into one passage, gives each passage a citation [n], and leaves out a passage that does not fit (it never cuts one). SContext holds the text with the markers (sText, uTokens), the citations (SCitation: number, document id and byte spans) and the same passages as blocks (SContextBlock). AddContextToRequest( Context, Request ) adds the blocks to an Ai::Llm request as text documents.
---
Threads and persistence
Queries run from any number of threads, each with its own CQuerySession. Upsert, Remove, Save and Compact wait for each other. A query sees the index as it was when it started. Compact builds the compacted index aside while queries keep running, and holds the writer lock only to swap it in. After warm-up, a query allocates nothing.
Save writes the files of a new generation, then the manifest, by a rename. A crash at any point leaves the previous snapshot whole. Open checks the size and SHA-256 of each file against the manifest (eChecksumMismatch) and refuses a snapshot of another configuration or model (eUnsupported).
Status codes (EStatus): eOk, eInvalidArgument, eOutOfMemory, eNotLicensed, eIoError, eFormatError, eEncodingError, eNotFound, eLimitExceeded (the capacity, or an input limit), eEmbeddingError (the provider failed, the index is unchanged), eChecksumMismatch, eUnsupported.
---
C layer
Header ethereal/c/ai/rag.h, 14 functions: ETLC_RagConfigDefault, ETLC_RagQueryDefault, ETLC_RagIndexCreate, ETLC_RagIndexOpen, ETLC_RagIndexDestroy, ETLC_RagUpsert (one document, with metadata), ETLC_RagRemove, ETLC_RagSave, ETLC_RagCompact, ETLC_RagCounts, ETLC_RagSessionCreate, ETLC_RagSessionDestroy, ETLC_RagSearch (with filters) and ETLC_RagBuildContext (the context text of the session's last query, with the required size on ETLC_ERR_BUFFER_TOO_SMALL). The provider is an ETLC_EmbedModel of ethereal/c/ai/embed.h, which must outlive the index, or NULL for a sparse only index. The query and passage prefixes go in ETLC_RagConfig.
In C, ingestion runs on the calling thread, tokens are counted as words, and there is no reranker, no remote provider, and no eDenseSearch or uEf choice. The loaders, the chunkers, the analyzer and the standalone BM25 index are C++ only. The status codes map to the common ETLC_ERR_* codes, plus ETLC_AI_RAG_EMBEDDING (-5816) when the embedding model fails.
---
What was measured
Correctness, against reference implementations:
- BM25 against rank_bm25: identical rankings, scores within 1e-5. Block-Max WAND against the exhaustive search: no difference in 1,800 queries, including a corpus built of tied scores.
- Stemmers against snowballstemmer 3.1.1: 100% agreement in English and Portuguese.
- Sentences on annotated text in English, Portuguese and Spanish: precision and recall 1.0.
- Dense search: exact mode equal to brute force, recall@10 of the graph at least 0.9.
Quality on NFCorpus (BEIR, 3,633 documents, 323 test queries) with e5-small-v2:
| Mode | nDCG@10 | Recall@10 |
|---|---|---|
| Dense | 0.326 | 0.149 |
| Sparse (BM25) | 0.328 | 0.158 |
| Hybrid (RRF) | 0.352 | 0.167 |
Speed on one million chunks, one thread. Intel i7-6700 (4 cores / 8 logical), GCC 15.2 on WSL2 and MSVC 19.51 native. The chunks are synthetic (20 words each, Zipf distributed) and the passage vectors come from a hash, so the dense part measures time, not quality. The hybrid query includes embedding the query with all-MiniLM-L6-v2 in int8. 500 queries each.
| Query | Target p50 | GCC p50 | GCC p99 | MSVC p50 | MSVC p99 |
|---|---|---|---|---|---|
| BM25 top 10 (query analysis included) | 2 ms | 1.57 ms | 19.7 ms | 1.73 ms | 22.4 ms |
| Hybrid top 10 | 10 ms | 7.94 ms | 29.1 ms | 7.41 ms | 33.0 ms |
Both targets are met. Ingesting the million chunks took 488 s on GCC (2,047 chunks per second, graph build included, no model time since the vectors come from a hash). With a real model, ingestion speed is bounded by Ai::Embed (see its page).
---
Known limits
- One chunker per index, set in
SIndexConfig::Chunking, whatever the document kind. - No stemmer for Spanish. Other languages work with
ELanguage::eNone(no stopwords, no stemming). uCapacityis fixed at creation: the vector index allocates for it up front, andUpsertpast it returnseLimitExceeded.- Only UTF-8 and UTF-16 with a BOM are read. No PDF or Office formats.