Ai::Rag

Beta

Hybrid search with an in-house BM25 and a vector index, with filters, diversification and context assembly with citations, within the token budget.

Optional module: turn it on with -DETHEREAL_AI_RAG=ONInclude #include <ethereal/cpp/ai/rag/rag_inc.hpp>C layer

rag_inc.hpp

#include <ethereal/cpp/ai/rag/rag_inc.hpp>

The whole of Ai::Rag.

rag_index.hpp

#include <ethereal/cpp/ai/rag/rag_index.hpp>

The index of Ai::Rag: the embedding providers (local by Ai::Embed, remote by Ai::Llm), the persistent embedding cache, the reranker hook, and CIndex (ingestion, hybrid query, context, snapshot, compaction).

C++
Embed::CModel Model;                      /// AI-06, loaded once
Rag::CLocalEmbedding Embedder( Model, "query: ", "passage: " );
Rag::SIndexConfig Config;
Config.sCachePath = "rag/embeddings.db";
Rag::CIndex Index;
Rag::CIndex::Create( Config, &Embedder, &Index );
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 R;
Index.Query( Q, Session, R );
Rag::SContext C;
Index.BuildContext( R, 1500, Session, C );  /// C.sText goes to the model
Index.Save( "rag/snapshot" );

Threads: queries from any number of threads at once (each with its session), one writer at a time (Upsert, Remove, Save, Compact wait for each other). A query sees the index as it was when it started. Compact may run on any thread while queries run: it builds the compacted index aside and only holds the writer lock to swap it in.

Persistence: Save writes the files of a new generation and then the manifest, by a rename. A failure (or a crash) at any point leaves the previous snapshot whole.

class

IEmbeddingProvider

Ethereal::Ai::Rag#

Where the vectors come from. Called from the writer and from the queries at the same time: an implementation must be thread safe. The vectors are normalized (the index compares by cosine).

class IEmbeddingProvider
function

ModelId

#
virtual std::string_view ModelId( void ) const noexcept = 0;

The id of the model: part of the key of the embedding cache.

function

Dimensions

#
virtual ETL_UINT32 Dimensions( void ) const noexcept = 0;
function

EmbedPassages

#
virtual EStatus EmbedPassages( const std::string_view * pTexts, std::size_t uCount, float * pOut ) noexcept = 0;

The vectors of uCount passages (uCount x Dimensions floats).

function

EmbedQuery

#
virtual EStatus EmbedQuery( std::string_view sText, float * pOut ) noexcept = 0;

The vector of a query (the query prefix of the model, when it has one).

destructor

~IEmbeddingProvider

#
virtual ~IEmbeddingProvider() = default;
class

CLocalEmbedding

Ethereal::Ai::Rag#

A model of Ai::Embed as provider, offline. Keeps one session per thread that calls it (a small pool), so the calls do not allocate once warm. The model must outlive the provider.

class CLocalEmbedding final : public IEmbeddingProvider
constructor

CLocalEmbedding

#
CLocalEmbedding( const Embed::CModel & Model, std::string_view sQueryPrefix = {}, std::string_view sPassagePrefix = {}, std::string_view sModelId = {} ) noexcept;
sModelId
The id for the cache. Empty takes a name from the model's description.
function

ModelId

#
std::string_view ModelId( void ) const noexcept override;
function

Dimensions

#
ETL_UINT32 Dimensions( void ) const noexcept override;
function

EmbedPassages

#
EStatus EmbedPassages( const std::string_view * pTexts, std::size_t uCount, float * pOut ) noexcept override;
function

EmbedQuery

#
EStatus EmbedQuery( std::string_view sText, float * pOut ) noexcept override;
class

CRemoteEmbedding

Ethereal::Ai::Rag#

The embeddings endpoint of a provider through Ai::Llm (OpenAI and the compatible servers). The vectors are normalized here. The client must outlive the provider. Without Ai::Llm in the build, every call is eUnsupported.

class CRemoteEmbedding final : public IEmbeddingProvider
constructor

CRemoteEmbedding

#
CRemoteEmbedding( Llm::CClient & Client, std::string_view sModel, ETL_UINT32 uDimensions, std::string_view sQueryPrefix = {}, std::string_view sPassagePrefix = {} ) noexcept;
function

ModelId

#
std::string_view ModelId( void ) const noexcept override;
function

Dimensions

#
ETL_UINT32 Dimensions( void ) const noexcept override;
function

EmbedPassages

#
EStatus EmbedPassages( const std::string_view * pTexts, std::size_t uCount, float * pOut ) noexcept override;
function

EmbedQuery

#
EStatus EmbedQuery( std::string_view sText, float * pOut ) noexcept override;
class

CEmbeddingCache

Ethereal::Ai::Rag#

Vectors by SHA-256 of the model id and the text, in a Storage database (one writer, many readers, crash safe). Reingesting a document whose chunks did not change computes nothing. Changing the model changes every key.

class CEmbeddingCache
constructor

CEmbeddingCache

#
CEmbeddingCache() noexcept = default;
function

Open

#
EStatus Open( std::string_view sPath ) noexcept;

Opens (or creates) the database at sPath.

function

Close

#
void Close( void ) noexcept;
function

IsOpen

#
bool IsOpen( void ) const noexcept
function

Get

#
bool Get( std::string_view sModel, std::string_view sText, float * pOut, ETL_UINT32 uDimensions ) const noexcept;

The vector of a text, when cached (false otherwise).

function

Put

#
EStatus Put( std::string_view sModel, const std::string_view * pTexts, const float * pVectors, std::size_t uCount, ETL_UINT32 uDimensions ) noexcept;

Stores the vectors of uCount texts in one transaction.

function

Hits

#
ETL_UINT64 Hits( void ) const noexcept;
function

Misses

#
ETL_UINT64 Misses( void ) const noexcept;
class

IReranker

Ethereal::Ai::Rag#

Scores the candidates of a query again (higher is better). Called from the query threads.

class IReranker
function

Rerank

#
virtual EStatus Rerank( std::string_view sQuery, const std::string_view * pPassages, std::size_t uCount, float * pScores ) noexcept = 0;
destructor

~IReranker

#
virtual ~IReranker() = default;
class

CLlmReranker

Ethereal::Ai::Rag#

A model of Ai::Llm scores the passages from 0 to 10 (it is asked for a JSON array of numbers, one per passage). A reply it cannot read leaves the order as it was. Without Ai::Llm in the build, Rerank is eUnsupported.

class CLlmReranker final : public IReranker
constructor

CLlmReranker

#
CLlmReranker( Llm::CClient & Client, std::string_view sModel ) noexcept;
function

Rerank

#
EStatus Rerank( std::string_view sQuery, const std::string_view * pPassages, std::size_t uCount, float * pScores ) noexcept override;
struct

SIndexConfig

Ethereal::Ai::Rag#
C++
struct   SIndexConfig
{
    SChunkConfig            Chunking;
    SAnalyzerConfig            Analyzer;
    SBm25Config                Bm25;

    /// @brief  The most chunks the dense index holds (VectorIndex allocates for them up front).
    ETL_UINT64                uCapacity = 100000u;
    ETL_UINT32                uM = 16u;
    ETL_UINT32                uEfConstruction = 200u;

    /// @brief  The embedding cache database. Empty: no cache.
    std::string                sCachePath;

    /// @brief  The token counter of the chunkers and of the context. Null counts words.
    const ITokenCounter *    pCounter = nullptr;

    /// @brief  The reranker of SQuery::bRerank. May be null.
    IReranker *                pReranker = nullptr;

    /// @brief  The threads of the ingestion (chunking and analysis in parallel). Null runs
    ///             on the calling thread.
    Job::IParallelFor *        pParallel = nullptr;

    /// @brief  Texts per call to the provider.
    ETL_UINT32                uEmbedBatch = 32u;

    /// @brief  Below this fraction of the chunks, the filters run before the search (a
    ///             bitmap); above it, after (with a fallback to before when too few pass).
    float                    fPrefilterBelow = 0.05f;
};
class

CQuerySession

Ethereal::Ai::Rag#

The workspace of one thread for queries: the buffers grow to the largest query and stay, so queries do not allocate once warm. The views of a result live until the next Query or BuildContext with the session.

class CQuerySession
constructor

CQuerySession

#
CQuerySession() noexcept;
class

CIndex

Ethereal::Ai::Rag#
class CIndex
constructor

CIndex

#
CIndex() noexcept = default;
function

Create

#
static EStatus Create( const SIndexConfig & Config, IEmbeddingProvider * pEmbedder, CIndex * pOut ) noexcept;

An empty index. The provider must outlive it (null: sparse only).

eOk, eInvalidArgument, eIoError (the cache), eOutOfMemory, eNotLicensed.
function

Open

#
static EStatus Open( std::string_view sDir, const SIndexConfig & Config, IEmbeddingProvider * pEmbedder, CIndex * pOut ) noexcept;

The snapshot in sDir (written by Save). The configuration must have the same chunking and analysis, and the provider the same model and dimensions.

eOk, eIoError, eFormatError, eChecksumMismatch, eUnsupported, eOutOfMemory.
function

Close

#
void Close( void ) noexcept;
function

Upsert

#
EStatus Upsert( const SDocument * pDocs, std::size_t uCount ) noexcept;

Adds the documents, replacing the ones with the same id. Chunks, analyzes and embeds them (the cache first), then publishes them at once: a query sees all of them or none.

eOk, eInvalidArgument (an empty id, the same id twice), eEmbeddingError, eLimitExceeded (the capacity), eOutOfMemory.
function

Remove

#
EStatus Remove( std::string_view sDocId ) noexcept;

Removes a document. eNotFound when it is not there.

function

Query

#
EStatus Query( const SQuery & Query, CQuerySession & Session, SQueryResult & Out ) const noexcept;

Dense, sparse or hybrid search, with the filters, the deduplication, MMR and the reranker the query asks for.

eOk, eInvalidArgument, eEmbeddingError, eUnsupported (dense without a provider), eOutOfMemory.
function

BuildContext

#
EStatus BuildContext( const SQueryResult & Result, ETL_UINT32 uTokenBudget, CQuerySession & Session, SContext & Out ) const noexcept;

The hits of Result packed into uTokenBudget tokens (the counter of the index), best first: adjacent or overlapping chunks of the same document become one passage, each passage gets a citation [n], and a passage that does not fit is left out (never cut).

function

Save

#
EStatus Save( std::string_view sDir ) noexcept;

Writes the snapshot in sDir (created when missing).

function

Compact

#
EStatus Compact( void ) noexcept;

Drops the removed chunks: rebuilds the segments into one and the dense index without them. Queries keep running during it.

function

Documents

#
std::size_t Documents( void ) const noexcept;
function

Chunks

#
std::size_t Chunks( void ) const noexcept;
function

Segments

#
std::size_t Segments( void ) const noexcept;
function

Config

#
const SIndexConfig & Config( void ) const noexcept;
function

DocumentText

#
EStatus DocumentText( std::string_view sDocId, std::string & Out ) const noexcept;

The text of a document in the index (a copy), or eNotFound.

function

Cache

#
const CEmbeddingCache * Cache( void ) const noexcept;

The embedding cache of the index (Hits, Misses), or null without one.

function

AddContextToRequest

Ethereal::Ai::Rag#
EStatus AddContextToRequest( const SContext & Context, Llm::CRequest & Request ) noexcept;

Adds the blocks of a context to a request of Ai::Llm as text documents (titled by the document id and the citation number). eUnsupported without Ai::Llm.

rag_text.hpp

#include <ethereal/cpp/ai/rag/rag_text.hpp>

The text side of Ai::Rag: the decoding, the loaders, the sentence splitter, the token counters, the chunkers, the analyzer with its stemmers, and the BM25 index.

All of it works on UTF-8 and on byte offsets of the text it was given. Nothing here needs an index: a program can chunk, analyze or rank with BM25 alone.

function

DecodeToUtf8

Ethereal::Ai::Rag#
EStatus DecodeToUtf8( std::span< const ETL_UINT8 > Bytes, std::string & Out ) noexcept;

UTF-8 (with or without BOM) or UTF-16 with BOM (LE or BE) into UTF-8 without BOM.

eOk, eEncodingError (anything else, invalid UTF-8 or UTF-16 included).
enum

ESourceKind

Ethereal::Ai::Rag#
C++
enum class   ESourceKind : ETL_UINT8 { eText = 0, eMarkdown, eCode, eHtml, eCsv, eJsonl };
function

KindFromPath

Ethereal::Ai::Rag#
ESourceKind KindFromPath( std::string_view sPath ) noexcept;

The kind of a file by its extension (unknown is eText).

struct

SLoaderOptions

Ethereal::Ai::Rag#
C++
struct   SLoaderOptions
{
    /// @brief  CSV and JSONL: the field of the text and of the id (no id field: the row
    ///             number, after the source id and '#'). The other scalar fields become
    ///             metadata (CSV: strings).
    std::string        sTextField = "text";
    std::string        sIdField = "id";
    char            cCsvSeparator = ',';
    std::size_t        uMaxBytes = std::size_t( 256u ) << 20;
};
function

LoadDocuments

Ethereal::Ai::Rag#
EStatus LoadDocuments( std::string_view sSourceId, std::span< const ETL_UINT8 > Bytes, ESourceKind eKind, const SLoaderOptions & Options, std::vector< SDocument > & Out ) noexcept;

The documents in Bytes: one for text, Markdown, code and HTML (the tags removed, the entities decoded, script and style dropped, block tags as line breaks), one per row for CSV (a header row first) and per line for JSONL.

sSourceId
The id of the document (or the prefix of the row ids).
Out
Replaced by the documents on eOk, untouched on an error.
eOk, eEncodingError, eFormatError (a broken CSV quote, a JSONL line that is not an object or lacks the text field), eLimitExceeded, eOutOfMemory.
function

LoadFile

Ethereal::Ai::Rag#
EStatus LoadFile( std::string_view sPath, const SLoaderOptions & Options, std::vector< SDocument > & Out ) noexcept;

The same from a file (the kind from the extension). eIoError when it does not read.

function

HtmlToText

Ethereal::Ai::Rag#
EStatus HtmlToText( std::string_view sHtml, std::string & Out ) noexcept;

The text of HTML without the markup (the extractor of the loader).

function

SplitSentences

Ethereal::Ai::Rag#
EStatus SplitSentences( std::string_view sText, ELanguage eLanguage, std::vector< SSpan > & Out ) noexcept;

The sentences of a text, as spans that start at the first character of each and end after its final punctuation (and closing quotes or brackets). The spaces between sentences belong to no span.

The rules: a sentence ends at '.', '!', '?', '…' (and the Spanish '¡' and '¿' start one) followed by a space and a capital, a digit or an opening punctuation, or at a blank line. Not at an abbreviation of the language ("Dr.", "Sr.", "etc." only before a capital that starts a name, "e.g."), an initial ("J. R. R."), a number ("3.14", "1.000,50"), an ellipsis inside a sentence, or a dot inside a URL or an e-mail.

class

ITokenCounter

Ethereal::Ai::Rag#

How the chunkers and the context count tokens. Called from several threads.

class ITokenCounter
function

Tokens

#
virtual EStatus Tokens( std::string_view sText, std::vector< SSpan > & Out ) const noexcept = 0;

The tokens of a text as byte spans (in order, non overlapping).

function

Count

#
virtual std::size_t Count( std::string_view sText ) const noexcept = 0;

The number of tokens of a text.

destructor

~ITokenCounter

#
virtual ~ITokenCounter() = default;
class

CWordCounter

Ethereal::Ai::Rag#

Words (runs of non spaces) as tokens. No model needed.

class CWordCounter final : public ITokenCounter
function

Tokens

#
EStatus Tokens( std::string_view sText, std::vector< SSpan > & Out ) const noexcept override;
function

Count

#
std::size_t Count( std::string_view sText ) const noexcept override;
class

CTokenizerCounter

Ethereal::Ai::Rag#

The tokens of a model (Ai::Tokenizer), so the budgets match what the model sees. The tokenizer must outlive the counter.

class CTokenizerCounter final : public ITokenCounter
constructor

CTokenizerCounter

#
explicit CTokenizerCounter( const Tokenizer::CTokenizer & Tok ) noexcept;
function

Tokens

#
EStatus Tokens( std::string_view sText, std::vector< SSpan > & Out ) const noexcept override;
function

Count

#
std::size_t Count( std::string_view sText ) const noexcept override;
function

ChunkText

Ethereal::Ai::Rag#
EStatus ChunkText( std::string_view sText, const SChunkConfig & Config, const ITokenCounter & Counter, std::vector< SChunk > & Out ) noexcept;

The chunks of one text by Config. No chunk goes over uMaxTokens (but a single token longer than it, which is its own chunk), no cut falls inside a code point, and without overlap the chunks tile the text exactly (chunk i ends where chunk i + 1 starts, the first starts at 0 and the last ends at the size).

eOk, eInvalidArgument (uMaxTokens zero, an overlap not below it), eOutOfMemory.
function

StemEnglish

Ethereal::Ai::Rag#
std::string StemEnglish( std::string_view sWord );

The Snowball English (Porter2, as revised in Snowball 3) stem of a lowercase word.

function

StemPortuguese

Ethereal::Ai::Rag#
std::string StemPortuguese( std::string_view sWord );

The Snowball Portuguese stem of a lowercase word (UTF-8).

function

IsStopword

Ethereal::Ai::Rag#
bool IsStopword( ELanguage eLanguage, std::string_view sWord ) noexcept;

Whether a lowercase word (accents removed or not, as the analyzer has it) is a stopword of the language.

class

CAnalyzer

Ethereal::Ai::Rag#

Text into terms: NFKC, lowercase, the accents removed (optional), words by the Unicode letters and digits, stopwords dropped and words stemmed (optional).

class CAnalyzer
constructor

CAnalyzer

#
explicit CAnalyzer( const SAnalyzerConfig & Config = {} ) noexcept;
function

Analyze

#
EStatus Analyze( std::string_view sText, std::vector< std::string > & Out ) noexcept;

The terms of a text, in order (repeated terms repeated). Out is cleared first. Reuses the scratch of the analyzer: one thread at a time.

function

Config

#
const SAnalyzerConfig & Config( void ) const noexcept
struct

SScored

Ethereal::Ai::Rag#
C++
struct   SScored
{
    ETL_UINT32        uDoc = 0u;
    float            fScore = 0.0f;
};

One result of BM25: the document and its score.

class

CBm25Index

Ethereal::Ai::Rag#

An inverted index of analyzed documents with BM25 ranking.

class CBm25Index

Postings by term in blocks of 128 documents (the gaps and the frequencies as varints), each block with the highest score any document in it can reach. Search runs Block-Max WAND, and gives exactly the top k of the exhaustive search, scores included: the contributions of a document are always summed in the order of the query terms. Ties go to the lower document number.

Build: Add the documents (numbers 0, 1, ...) and Finalize. After Finalize the index is read only and Search may run from several threads.

constructor

CBm25Index

#
explicit CBm25Index( const SBm25Config & Config = {} ) noexcept;
constructor

CBm25Index

#
CBm25Index( CBm25Index && Other ) noexcept;
operator

operator=

#
CBm25Index & operator=( CBm25Index && Other ) noexcept;
function

Add

#
EStatus Add( std::span< const std::string > Terms ) noexcept;

The next document (its number is the count so far). Before Finalize.

function

Finalize

#
EStatus Finalize( void ) noexcept;

Compresses the postings and computes the idf and the block maxima.

function

SearchExhaustive

#
EStatus SearchExhaustive( std::span< const std::string > Terms, std::size_t uK, std::vector< SScored > & Out, const ETL_UINT64 * pAllow = nullptr ) const noexcept;

The same by scoring every document (the reference of the tests).

function

Score

#
float Score( std::span< const std::string > Terms, ETL_UINT32 uDoc ) const noexcept;

The BM25 score of one document.

function

Documents

#
ETL_UINT32 Documents( void ) const noexcept;
function

Terms

#
std::size_t Terms( void ) const noexcept;
function

PostingBytes

#
std::size_t PostingBytes( void ) const noexcept;
function

Serialize

#
EStatus Serialize( std::string & Out ) const noexcept;

The serialized form (after Finalize), and the index back from it.

function

Deserialize

#
static EStatus Deserialize( std::string_view sData, CBm25Index * pOut ) noexcept;

rag_types.hpp

#include <ethereal/cpp/ai/rag/rag_types.hpp>

Types of Ai::Rag: the status codes, the documents and their metadata, the chunks, the configurations of the chunkers, of the analyzer, of BM25 and of an index, and the query, its result and the context built from it.

enum

EStatus

Ethereal::Ai::Rag#
C++
enum class   EStatus : ETL_UINT8
{
    eOk = 0,
    eInvalidArgument,
    eOutOfMemory,
    eNotLicensed,
    eIoError,            /// A file could not be read, written, renamed or mapped.
    eFormatError,        /// A file or a record that is not what it says (CSV, JSONL, a snapshot).
    eEncodingError,        /// Text in an encoding the module does not read (only UTF-8 and UTF-16 with BOM).
    eNotFound,            /// A document id that is not in the index.
    eLimitExceeded,        /// The capacity of the index, or a limit of the input.
    eEmbeddingError,    /// The embedding provider failed.
    eChecksumMismatch,    /// A snapshot whose file does not match the manifest.
    eUnsupported        /// A snapshot made with another configuration (the dimensions, the model).
};
function

StatusName

Ethereal::Ai::Rag#
const char * StatusName( EStatus eStatus ) noexcept;

The name of a status, in English.

enum

EMetaType

Ethereal::Ai::Rag#
C++
enum class   EMetaType : ETL_UINT8 { eString = 0, eInt, eReal, eBool, eDate };

The type of a metadata value. A date is days since 1970-01-01 (UTC), so it orders and compares as an integer.

struct

SMetaValue

Ethereal::Ai::Rag#
C++
struct   SMetaValue
{
    EMetaType        eType = EMetaType::eString;
    std::string        sString;
    ETL_INT64        iInt = 0;        /// eInt, eDate (days), eBool (0 or 1).
    double            dReal = 0.0;

    static SMetaValue String( std::string_view s ) { SMetaValue v; v.sString.assign( s ); return v; }
    static SMetaValue Int( ETL_INT64 i ) { SMetaValue v; v.eType = EMetaType::eInt; v.iInt = i; return v; }
    static SMetaValue Real( double d ) { SMetaValue v; v.eType = EMetaType::eReal; v.dReal = d; return v; }
    static SMetaValue Bool( bool b ) { SMetaValue v; v.eType = EMetaType::eBool; v.iInt = b ? 1 : 0; return v; }
    static SMetaValue Date( ETL_INT64 iDays ) { SMetaValue v; v.eType = EMetaType::eDate; v.iInt = iDays; return v; }
};
struct

SMeta

Ethereal::Ai::Rag#
C++
struct   SMeta
{
    std::string        sKey;
    SMetaValue        Value;
};
alias

EStatus

Ethereal::Ai::Rag#
using PFN_LoadText = EStatus ( * )( void * pUser, std::string_view sId, std::string & sOut );

Fills sOut with the text of document sId, for a document whose text is loaded only when it is indexed.

struct

SDocument

Ethereal::Ai::Rag#
C++
struct   SDocument
{
    std::string                sId;
    std::string                sText;
    std::vector< SMeta >    Meta;

    /// @brief  When not null, called instead of reading sText (lazy loading).
    PFN_LoadText            pfnLoad = nullptr;
    void *                    pLoadUser = nullptr;
};

A document: a stable id chosen by the user, the text (or a loader), and the metadata.

enum

ELanguage

Ethereal::Ai::Rag#
C++
enum class   ELanguage : ETL_UINT8 { eNone = 0, eEnglish, ePortuguese, eSpanish };

The languages of the sentence splitter, the stopwords and the stemmers.

struct

SSpan

Ethereal::Ai::Rag#
C++
struct   SSpan
{
    std::size_t        uBegin = 0u;
    std::size_t        uEnd = 0u;
};

A span of bytes of a text.

enum

EChunker

Ethereal::Ai::Rag#
C++
enum class   EChunker : ETL_UINT8
{
    eFixedTokens = 0,    /// Windows of uMaxTokens tokens, each starting uMaxTokens - uOverlapTokens after the last.
    eRecursive,            /// Paragraphs, then sentences, then words, merged up to the budget.
    eMarkdown,            /// The sections of the headings, each chunked recursively, the heading path recorded.
    eCode                /// Function and block boundaries by braces and indentation, merged up to the budget.
};
struct

SChunkConfig

Ethereal::Ai::Rag#
C++
struct   SChunkConfig
{
    EChunker        eChunker = EChunker::eRecursive;
    ETL_UINT32        uMaxTokens = 256u;
    ETL_UINT32        uOverlapTokens = 32u;        /// eFixedTokens only.
    ELanguage        eLanguage = ELanguage::eEnglish;    /// The sentence splitter of eRecursive and eMarkdown.
};
struct

SChunk

Ethereal::Ai::Rag#
C++
struct   SChunk
{
    std::size_t        uBegin = 0u;
    std::size_t        uEnd = 0u;
    ETL_UINT32        uTokens = 0u;
    std::string        sHeadingPath;    /// eMarkdown: "Title > Section > Subsection".
};

A piece of a document: the bytes [uBegin, uEnd) of its text, never in the middle of a code point. Without overlap, the chunks of a document tile it.

struct

SAnalyzerConfig

Ethereal::Ai::Rag#
C++
struct   SAnalyzerConfig
{
    ELanguage        eLanguage = ELanguage::eEnglish;
    bool            bRemoveAccents = true;
    bool            bStopwords = true;
    bool            bStem = true;        /// English and Portuguese (no stemmer for the others).
    bool            bWhitespace = false;    /// Split on spaces only, nothing else (pre-tokenized text, the tests).
};
enum

EIdf

Ethereal::Ai::Rag#
C++
enum class   EIdf : ETL_UINT8 { eLucene = 0, eOkapi };

The idf of BM25. eLucene, ln( 1 + ( N - df + 0.5 ) / ( df + 0.5 ) ), is never negative. eOkapi is the BM25Okapi of rank_bm25: ln( ( N - df + 0.5 ) / ( df + 0.5 ) ), a negative value replaced by 0.25 times the mean idf.

struct

SBm25Config

Ethereal::Ai::Rag#
C++
struct   SBm25Config
{
    float            fK1 = 1.2f;
    float            fB = 0.75f;
    EIdf            eIdf = EIdf::eLucene;
};
enum

EQueryMode

Ethereal::Ai::Rag#
C++
enum class   EQueryMode : ETL_UINT8 { eDense = 0, eSparse, eHybrid };
enum

EFusion

Ethereal::Ai::Rag#
C++
enum class   EFusion : ETL_UINT8 { eRrf = 0, eWeighted };
enum

EFilterOp

Ethereal::Ai::Rag#
C++
enum class   EFilterOp : ETL_UINT8 { eEqual = 0, eRange, eIn };
struct

SFilter

Ethereal::Ai::Rag#
C++
struct   SFilter
{
    std::string                    sKey;
    EFilterOp                    eOp = EFilterOp::eEqual;
    SMetaValue                    Value;        /// eEqual.
    SMetaValue                    Low;        /// eRange.
    SMetaValue                    High;        /// eRange.
    std::vector< SMetaValue >    Values;        /// eIn.
};

One condition on a metadata key. The conditions of a query are ANDed. eRange is [Low, High] (both included) on numbers and dates. eIn is any of Values.

enum

EDenseSearch

Ethereal::Ai::Rag#
C++
enum class   EDenseSearch : ETL_UINT8 { eAuto = 0, eExact, eGraph };

How the dense search runs: the automatic choice of VectorIndex, the exact brute force, or the graph.

struct

SQuery

Ethereal::Ai::Rag#
C++
struct   SQuery
{
    std::string_view            sText;
    EQueryMode                    eMode = EQueryMode::eHybrid;
    ETL_UINT32                    uTopK = 10u;
    ETL_UINT32                    uCandidates = 50u;        /// Per list before the fusion, the reranker, MMR and dedup. A sparse only query with none of them takes uTopK.
    EFusion                        eFusion = EFusion::eRrf;
    float                        fRrfK = 60.0f;
    float                        fDenseWeight = 0.5f;    /// eWeighted: dense * w + sparse * ( 1 - w ), each min-max normalized.
    const SFilter *                pFilters = nullptr;
    std::size_t                    uFilters = 0u;
    float                        fMmrLambda = 1.0f;        /// 1 is no MMR. Lower trades relevance for diversity.
    float                        fDedupCosine = 1.0f;    /// Below 1, a chunk this close to one already taken is dropped.
    EDenseSearch                eDenseSearch = EDenseSearch::eAuto;
    ETL_UINT32                    uEf = 64u;
    bool                        bRerank = false;        /// Run the reranker of the index on the candidates.
};
struct

SHit

Ethereal::Ai::Rag#
C++
struct   SHit
{
    ETL_UINT64            uChunk = 0u;        /// The id of the chunk in the index.
    std::string_view    sDocId;                /// Valid while the result lives.
    std::size_t            uBegin = 0u;        /// The bytes of the chunk in the text of its document.
    std::size_t            uEnd = 0u;
    float                fScore = 0.0f;        /// After the fusion (and the reranker).
    float                fSparse = 0.0f;        /// BM25, 0 when not in the sparse list.
    float                fDense = 0.0f;        /// Cosine similarity, 0 when not in the dense list.
    ETL_INT32            iSparseRank = -1;    /// The rank in each list, -1 when absent.
    ETL_INT32            iDenseRank = -1;
};
struct

SQueryResult

Ethereal::Ai::Rag#
C++
struct   SQueryResult
{
    std::vector< SHit >        Hits;
    bool                    bPrefiltered = false;    /// The filters ran before the search (selective).
};
struct

SCitation

Ethereal::Ai::Rag#
C++
struct   SCitation
{
    ETL_UINT32                uNumber = 0u;
    std::string                sDocId;
    std::vector< SSpan >    Spans;
};

A citation marker [n] of the context: the document and the byte ranges of its text that the passage holds (adjacent chunks are merged).

struct

SContextBlock

Ethereal::Ai::Rag#
C++
struct   SContextBlock
{
    ETL_UINT32        uCitation = 0u;
    std::string        sTitle;        /// The document id.
    std::string        sText;
};
struct

SContext

Ethereal::Ai::Rag#
C++
struct   SContext
{
    std::string                        sText;
    ETL_UINT32                        uTokens = 0u;
    std::vector< SCitation >        Citations;
    std::vector< SContextBlock >    Blocks;
};

The passages of a result packed into a token budget: as one text with citation markers, and as document blocks for Ai::Llm.