Ai::Llm

Beta

One API for Anthropic, OpenAI and servers compatible with the OpenAI API, with streaming that allocates nothing per event, a connection pool, smart retries and cost control.

Optional module: turn it on with -DETHEREAL_AI_LLM=ONInclude #include <ethereal/cpp/ai/llm/llm_inc.hpp>C layer

llm_inc.hpp

#include <ethereal/cpp/ai/llm/llm_inc.hpp>

Everything of the Ai::Llm module, in one include.

Needs the library built with ETHEREAL_AI_LLM (the macro ETL_AI_LLM is then defined).

llm_arena.hpp

#include <ethereal/cpp/ai/llm/llm_arena.hpp>

CArena: the bump arena of a request and of its response.

Memory::CMemoryArena was not reused: it takes its chunks from malloc, not from a Memory::IAllocator the user can inject, it frees the extra chunks on Reset (so a request that grew would allocate again on every reuse), and it locks a mutex on every allocation.

class

CArena

Ethereal::Ai::Llm#

A bump arena over chunks taken from a Memory::IAllocator.

class CArena

Reset keeps every chunk, so a request reused after the first one does not allocate again unless it grows. A block larger than the chunk size gets a chunk of its own, also kept. Release gives every chunk back.

For the exclusive use of one thread.
const

kDefaultChunkBytes

#
static constexpr std::size_t kDefaultChunkBytes = 16384u;

Default size of a chunk, in bytes.

constructor

CArena

#
explicit CArena( Memory::IAllocator * pAllocator = nullptr, std::size_t uChunkBytes = 0 ) noexcept;

An empty arena. Nothing is allocated until the first block.

pAllocator
Source of the chunks. Null is Memory::DefaultAllocator.
uChunkBytes
Size of a chunk. Zero is kDefaultChunkBytes.
function

Allocate

#
void * Allocate( std::size_t uBytes, std::size_t uAlign = alignof( std::max_align_t ) ) noexcept;

A block of uBytes bytes aligned to uAlign (a power of two, up to alignof( std::max_align_t )).

The block, or null when the allocator failed or the alignment is not supported. Zero bytes gives a valid pointer.
function

Copy

#
bool Copy( std::string_view sText, std::string_view & Out ) noexcept;

Copies sText into the arena.

sText
The text. Empty gives an empty view and allocates nothing.
Out
The copy.
False when the allocator failed.
function

Reset

#
void Reset( void ) noexcept;

Forgets every block and keeps the chunks.

function

Release

#
void Release( void ) noexcept;

Gives every chunk back to the allocator.

function

Reserved

#
std::size_t Reserved( void ) const noexcept;

Bytes held in chunks, used or not.

function

Used

#
std::size_t Used( void ) const noexcept

Bytes handed out since the last Reset, alignment padding included.

function

Allocator

#
Memory::IAllocator * Allocator( void ) const noexcept

The allocator of the chunks.

llm_check.hpp

#include <ethereal/cpp/ai/llm/llm_check.hpp>

Tools and structured output with the schemas of AI-02: which dialect each provider is given, the lookup of a tool, the message of a check for the model, and the typed decode of a tool input or of the structured output.

The checks themselves run inside ParseResponse and CStreamDecoder, as the response arrives (CRequest::SetCheckMode). A stream feeds each piece of a tool input to the streaming validator of AI-02, so a value that can no longer be valid is seen at the byte that decides it.

function

ToolDialect

Ethereal::Ai::Llm#
Schema::EDialect ToolDialect( EProvider eProvider, bool bStrict ) noexcept;

The dialect of the schema of a tool for a provider.

Anthropic: eAnthropicStrict with 'strict', eAnthropic without. OpenAI and the compatible servers: eOpenAIStrict with 'strict', eGeneric without.

function

OutputDialect

Ethereal::Ai::Llm#
Schema::EDialect OutputDialect( EProvider eProvider, bool bStrict ) noexcept;

The dialect of the schema of the structured output for a provider.

Anthropic: eAnthropicStrict always ('output_config.format' is constrained decoding, with the rules of strict mode). OpenAI and the compatible servers: eOpenAIStrict with 'strict', eGeneric without.

function

FindTool

Ethereal::Ai::Llm#
const STool * FindTool( const CRequest & Request, std::string_view sName ) noexcept;

The portable tool of Request with this name, or null.

function

OutputText

Ethereal::Ai::Llm#
std::string_view OutputText( CRequest & Request, const SResponse & Response ) noexcept;

The structured output of a response: the text of its text block, or the texts of all of them joined in the response arena of Request when there are many.

The text, or empty (no text block, or no memory to join them).
function

FormatCheck

Ethereal::Ai::Llm#
std::size_t FormatCheck( const SCheck & Check, std::span< char > Out ) noexcept;

A short message about a check, in English, for the model that wrote the value: the text of a tool result with 'is_error'.

"at /unit: value is not one of the enum values (celsius)", "not JSON at byte 17: unexpected character", "the value is incomplete", "valid". The message is cut to fit, and always ends with a zero.

Check
The verdict.
Out
Destination. Empty writes nothing.
The length written, without the zero.
function

DecodeToolInput

Ethereal::Ai::Llm#
template < typename T > Schema::EStatus DecodeToolInput( const CRequest & Request, const EProvider eProvider, const SBlock & Block, T & Out, Schema::SValidationReport & Report, Memory::CMemoryArena * const pArena = nullptr ) noexcept

Decodes the input of a tool use into the described type T, with the checks of the whole type (Schema::Decode).

The dialect comes from the tool of the same name in Request: a strict tool of OpenAI writes an optional field as null. A tool that is not in the request decodes as eGeneric. The decoder allocates on each call: to decode many inputs, keep a Schema::CDecoder with the options of ToolDialect.

Request
The request the response answered.
eProvider
Its provider.
Block
A tool use block.
Out
Receives the value.
Report
Receives the result.
pArena
Where views with escapes and spans go (see Schema::CDecoder).
Report.eStatus. eInvalidArgument for a block that is not a tool use.
function

DecodeOutput

Ethereal::Ai::Llm#
template < typename T > Schema::EStatus DecodeOutput( CRequest & Request, const EProvider eProvider, const SResponse & Response, T & Out, Schema::SValidationReport & Report, Memory::CMemoryArena * const pArena = nullptr ) noexcept

Decodes the structured output of a response (OutputText) into the described type T, with the dialect of the request (OutputDialect).

Report.eStatus. eInvalidArgument when the response has no text.

llm_client.hpp

#include <ethereal/cpp/ai/llm/llm_client.hpp>

The client of the Llm module: a request goes to the provider and comes back as an SResponse, whole or streamed, synchronous or asynchronous.

The client puts together the body written by WriteRequestBody, the transport of the Http module (the keep-alive pool, TLS, the four time limits, cancellation, gzip), and the response read by ParseResponse, ParseError or CStreamDecoder.

The key of the API is copied into a buffer of the client that is wiped when the client goes away. It is sent in the header the provider expects (x-api-key, or Authorization: Bearer), and never goes into a result, an error text or a log line of the module.

Stage 4 added the resilience: a request that failed for a reason worth repeating (a broken connection, 408, 429, 5xx, an overloaded provider) is sent again with exponential backoff and jitter, or after the retry-after the provider asked for. A stream that already handed content to the caller is not sent again unless the caller allows it. A circuit breaker stops sending to a provider that keeps failing, and a rate limiter (requests and tokens per minute, and the limits the provider announces in its headers) makes requests wait their turn.

alias

ETL_UINT64

Ethereal::Ai::Llm#
using PFN_EstimateTokens = ETL_UINT64 ( * )( void * pUser, const CRequest & Request, std::size_t uBodyBytes );

Estimates the tokens a request will spend, for the tokens per minute limit.

pUser
SRateLimits::pEstimateUser.
Request
The request.
uBodyBytes
The size of the body written for it.
The tokens, input and output together.
alias

void

Ethereal::Ai::Llm#
using PFN_Sleep = void ( * )( void * pUser, ETL_UINT64 uNs );

Waits on the calling thread, for the waits of the synchronous calls. A test replaces it with one that moves a manual clock.

struct

SRetryConfig

Ethereal::Ai::Llm#
C++
struct   SRetryConfig
{
    /// @brief  Attempts in all, the first one included. One sends once. The official
    ///             SDKs of both providers retry twice.
    ETL_UINT32        uMaxAttempts = 3u;

    /// @brief  The first backoff, and the largest, in milliseconds (exponential, full
    ///             jitter).
    ETL_UINT64        uBaseDelayMs = 500u;
    ETL_UINT64        uMaxDelayMs = 8000u;

    /// @brief  A retry-after longer than this is not waited for: the error comes back.
    ETL_UINT64        uMaxRetryAfterMs = 60000u;

    /// @brief  Time for all the attempts and waits together. Zero is no limit.
    ETL_UINT64        uTotalBudgetMs = 0u;

    /// @brief  Send a stream again even after events with content reached the caller.
    ///             The caller then sees a new eMessageStart, and must start over from it.
    bool            bRetryAfterContent = false;
};

When and how a failed request is sent again.

What is repeated: a connection that failed (the name, TCP, a TLS handshake that broke, not one that refused the certificate), the connect time limit, a stream cut before it ended, and the provider errors SError::bRetryable marks (408, 429 that is not a quota, 500, 502, 503, 504, 529, overloaded). Never: a request the provider refused for what it holds, a cancellation, a first byte or idle time limit (the model may have been working), or a stream that already handed content to the caller (unless bRetryAfterContent).

struct

SRateLimits

Ethereal::Ai::Llm#
C++
struct   SRateLimits
{
    /// @brief  Requests per minute (each attempt counts).
    ETL_UINT32                uRequestsPerMinute = 0u;

    /// @brief  Tokens per minute, estimated before the request and corrected by the usage
    ///             the response reports.
    ETL_UINT64                uTokensPerMinute = 0u;

    /// @brief  The longest a request waits for its turn. Longer, it fails with
    ///             eRateLimited.
    ETL_UINT64                uMaxWaitMs = 60000u;

    /// @brief  Follow the limits the provider announces in its response headers: when
    ///             one of them runs out, the next requests wait for its reset.
    bool                    bFollowServerHeaders = true;

    /// @brief  The estimate of the tokens of a request. Null: the bytes of the body over
    ///             four, plus the max_tokens of the request. A tokenizer of the AI-01
    ///             module gives a better one.
    PFN_EstimateTokens        pfnEstimate = nullptr;
    void *                    pEstimateUser = nullptr;
};

The rate limit of the client. Zero in a limit is no limit.

struct

SClientConfig

Ethereal::Ai::Llm#
C++
struct   SClientConfig
{
    /// @brief  The API, the Anthropic version and the compatibility flags.
    SProviderOptions                Provider;

    /// @brief  The base URL, as the official SDK of the provider takes it. Empty: the
    ///             public endpoint of the provider ('https://api.anthropic.com' for
    ///             Anthropic, 'https://api.openai.com/v1' for OpenAI). Required for
    ///             eOpenAiCompatible ('http://localhost:11434/v1'). The client appends
    ///             '/v1/messages' (Anthropic) or '/chat/completions' (the others).
    std::string_view                sBaseUrl;

    /// @brief  The key of the API. Copied, and wiped with the client.
    std::string_view                sApiKey;

    /// @brief  The environment variable read when sApiKey is empty. Empty: the one of
    ///             the provider ('ANTHROPIC_API_KEY', 'OPENAI_API_KEY'). A compatible server
    ///             may run without a key, and then no key is sent.
    std::string_view                sApiKeyEnv;

    /// @brief  Headers sent with every request ('anthropic-beta', 'OpenAI-Project').
    ///             Copied. The client writes the key, the version and the content type itself,
    ///             and refuses them here.
    std::span< const Http::SHeader >    Headers;

    /// @brief  The time limits of a request, unless the call gives its own.
    Http::STimeouts                    Timeouts;

    /// @brief  The transport: the pool, the roots of TLS, the pin, the limits of the
    ///             HTTP reader.
    Http::SClientOptions            Http;

    /// @brief  true runs the asynchronous requests on a thread of the client (the
    ///             default). false leaves the loop to the caller, who calls RunAsync.
    bool                            bAsyncOwnThread = true;

    /// @brief  The allocator of the stream decoders and of the buffers. Null: the
    ///             default one.
    Memory::IAllocator *            pAllocator = nullptr;

    /// @brief  The retry (stage 4).
    SRetryConfig                    Retry;

    /// @brief  The rate limit (stage 4).
    SRateLimits                        RateLimits;

    /// @brief  Use the circuit breaker (stage 4), with Breaker as its policy.
    bool                            bBreaker = true;
    Resilience::SBreakerPolicy        Breaker;

    /// @brief  The clock of the backoff, of the rate limit and of the breaker. Null: the
    ///             system one. Not owned: it must outlive the client.
    Resilience::IClock *            pClock = nullptr;

    /// @brief  The wait of the synchronous calls. Null: the thread sleeps (waking for
    ///             the cancellation token).
    PFN_Sleep                        pfnSleep = nullptr;
    void *                            pSleepUser = nullptr;

    /// @brief  A ledger shared by many clients, where this one also records its usage
    ///             (stage 6). Null: only the ledger of the client. Not owned: it must
    ///             outlive the client.
    CUsageLedger *                    pSharedUsage = nullptr;

    /// @brief  The tracer of the Telemetry module: one client span per call (stage 7),
    ///             child of the context of the calling thread, with the provider, the
    ///             operation, the models, the attempts, the HTTP status, the tokens and the id
    ///             of the request. Never the content of the messages, never the key. Used only
    ///             when the library is built with ETHEREAL_TELEMETRY. Null: no span. Not owned.
    Telemetry::CTracer *            pTracer = nullptr;
};

How a client reaches its provider.

struct

SCallResult

Ethereal::Ai::Llm#
C++
struct   SCallResult
{
    /// @brief  The status, the same the call returns.
    EStatus                eStatus = EStatus::eOk;

    /// @brief  The error of the provider, with EStatus::eProviderError: an HTTP status
    ///             that is not 2xx, or an error event inside a stream. The views point into
    ///             the response arena of the request.
    SError                Error;

    /// @brief  The transport of the last attempt: the HTTP status, which time limit ran
    ///             out, the system and TLS errors, whether the connection came from the pool,
    ///             the times.
    Http::SResult        Http;

    /// @brief  Attempts made (zero when the breaker or the rate limit stopped the first).
    ETL_UINT32            uAttempts = 0u;

    /// @brief  Milliseconds spent waiting: the backoff, the retry-after, the rate limit.
    ETL_UINT64            uWaitedMs = 0u;

    /// @brief  A stream handed content to the caller: a block or a delta (not the start,
    ///             the usage, the end, a ping or an error).
    bool                bContentDelivered = false;
};

What happened to a request.

alias

void

Ethereal::Ai::Llm#
using PFN_OnDone = void ( * )( void * pUser, const SCallResult & Result, const SResponse & Response );

Called once when an asynchronous request ends, on the loop thread.

pUser
The pointer given to StartAsync.
Result
What happened.
Response
The response, complete with eOk. Its views point into the response arena of the request, valid until the request is used again.
class

CClient

Ethereal::Ai::Llm#

A client of one provider.

class CClient
C++
Llm::SClientConfig Config;
Config.Provider.eProvider = Llm::EProvider::eAnthropic;
Llm::CClient Client( Config );            // the key from ANTHROPIC_API_KEY
Llm::CRequest Request;
Request.SetModel( sModel );
Request.SetMaxTokens( 1024 );
Request.AddMessage( Llm::ERole::eUser );
Request.AddText( "Hello" );
Llm::SResponse Response;
Llm::SCallResult Result;
Client.Stream( Request, &OnEvent, &Context, Response, Result );

A request object is used by one call at a time: the response lives in its arena. Different requests can go out at the same time on the same client. Nothing is allocated per request once the pool holds the connections and the client has kept the buffers of as many requests as run at once.

Thread safe: Send, Stream, StartAsync, Cancel and Stats can be called from several threads at once. The client must not be destroyed while a call runs.
constructor

CClient

#
explicit CClient( const SClientConfig & Config );

A client for the configuration. Status says whether it is usable.

function

Status

#
EStatus Status( void ) const noexcept

eOk, or why the client cannot send: eInvalidArgument (a bad base URL, a missing key for Anthropic or OpenAI, a header the client owns), eOutOfMemory or eNotLicensed.

function

Send

#
EStatus Send( CRequest & Request, SResponse & Response, SCallResult & Result, const Http::STimeouts * pTimeouts = nullptr, const Http::CCancelToken * pCancel = nullptr ) noexcept;

Sends a request and reads the whole response.

Send

Request
The request. Its response arena receives the response.
Response
Receives the response, with eOk.
Result
Receives what happened.
pTimeouts
The time limits of this call, or null for those of the client.
pCancel
A token that stops the call, or null.
The same as Result.eStatus.
function

Stream

#
EStatus Stream( CRequest & Request, PFN_OnStreamEvent pfnOnEvent, void * pUser, SResponse & Response, SCallResult & Result, const Http::STimeouts * pTimeouts = nullptr, const Http::CCancelToken * pCancel = nullptr ) noexcept;

Sends a request for a streamed response and hands each event to pfnOnEvent as it arrives, on the calling thread.

Stream When the server answers a streamed request with a whole JSON body (some compatible servers do), the body is read as a response that was not streamed, and no event comes.

As Send.
function

StartAsync

#
EStatus StartAsync( CRequest & Request, bool bStream, PFN_OnStreamEvent pfnOnEvent, PFN_OnDone pfnDone, void * pUser, std::uint64_t * pId = nullptr, const Http::STimeouts * pTimeouts = nullptr ) noexcept;

Starts a request and returns at once.

StartAsync The body is written here, from the request. The request must then stay alive and untouched until pfnDone: the response is built in its arena. The events (with bStream) and pfnDone come on the loop thread.

Request
The request.
bStream
Asks for a streamed response.
pfnOnEvent
The events of the stream, or null.
pfnDone
Called once at the end. Can be null.
pUser
Passed to both.
pId
Receives the id of the request, for Cancel. Can be null.
pTimeouts
The time limits of this call, or null for those of the client.
eOk when the request was accepted, and then pfnDone comes once. Otherwise the reason, and no callback comes.
function

Cancel

#
bool Cancel( std::uint64_t Id ) noexcept;

Stops an asynchronous request. Safe from any thread. The request ends with eCancelled, unless it ended first.

function

RunAsync

#
std::size_t RunAsync( ETL_UINT32 uTimeoutMs ) noexcept;

Runs the loop of the asynchronous requests for at most uTimeoutMs, when SClientConfig::bAsyncOwnThread is false.

function

Stats

#
Http::SClientStats Stats( void ) const noexcept;

The counters of the transport, the synchronous and the asynchronous pools added up.

function

CountTokens

#
EStatus CountTokens( CRequest & Request, ETL_UINT64 & uInputTokens, SCallResult & Result, const Http::STimeouts * pTimeouts = nullptr, const Http::CCancelToken * pCancel = nullptr ) noexcept;

Counts the input tokens of a request through the counting endpoint of Anthropic (POST /v1/messages/count_tokens), with the retry and the breaker of the client.

CountTokens The count does not go through the rate limit of the client: the endpoint is free and has limits of its own. A 429 is still repeated after its retry-after.

Request
The request, written without the fields of generation (WriteCountTokensBody).
uInputTokens
Receives the count.
As Send, and eUnsupported for OpenAI and the compatible servers, which count locally (CountTokensLocal).
function

Embed

#
EStatus Embed( const SEmbedRequest & Request, CEmbedResult & Out, SCallResult & Result, const Http::STimeouts * pTimeouts = nullptr, const Http::CCancelToken * pCancel = nullptr ) noexcept;

Gets the embeddings of the inputs from the embeddings endpoint (OpenAI and the compatible servers), with the retry, the breaker and the rate limit of the client.

Embed

Request
The inputs. Only needs to live during the call.
Out
Receives the vectors, in the order of the inputs. The texts of an error of the provider (Result.Error) live in its arena too.
As Send, and eUnsupported for Anthropic, which has no embeddings.
function

UsageTotal

#
SUsageTotals UsageTotal( void ) const noexcept;

The usage this client recorded: one per response that carried usage (every attempt that billed, retries included), by model (the one that answered) and by the tag of the request.

function

UsageEntries

#
std::size_t UsageEntries( std::span< SUsageEntry > Out ) const noexcept;

The entries of the usage of this client (CUsageLedger::Entries).

function

ResetUsage

#
void ResetUsage( void ) noexcept;

Forgets the usage of this client.

function

CallStateBytes

#
std::size_t CallStateBytes( void ) const noexcept;

Diagnostic: the largest state of one call kept by the client, in bytes (the control of the call and the buffers of its stream decoder), without the bodies, the arenas of the request and the connections of the pool, which belong to the payload and to the transport (stage 7, L4).

llm_embed.hpp

#include <ethereal/cpp/ai/llm/llm_embed.hpp>

Remote embeddings: the request, the result over an arena, and the body and the response of the embeddings endpoint of OpenAI and of the compatible servers (CClient::Embed).

The format comes from the official reference, read on 13-11-2026 and again on 20-11-2026. Anthropic has no embeddings endpoint.

Only 'encoding_format' "float" is asked for: the reference does not say what the bytes of "base64" are, and the module does not guess a format (L63).

const

kEmbedMaxInputs

Ethereal::Ai::Llm#
inline constexpr ETL_UINT32 kEmbedMaxInputs = 2048u;

Most inputs of one request (the limit of the OpenAI reference).

struct

SEmbedRequest

Ethereal::Ai::Llm#
C++
struct   SEmbedRequest
{
    /// @brief  The model ("text-embedding-3-small"). Required.
    std::string_view                    sModel;

    /// @brief  The texts, 1 to kEmbedMaxInputs, none empty (the reference refuses an
    ///             empty string). The views only need to live during the call.
    std::span< const std::string_view >    Inputs;

    /// @brief  The size of the vectors, or 0 for the default of the model. Only the
    ///             models from text-embedding-3 on take it.
    ETL_UINT32                            uDimensions = 0;

    /// @brief  The 'user' of OpenAI (abuse monitoring). May be empty.
    std::string_view                    sUser;

    /// @brief  The tag under which the usage is recorded (CUsageLedger). May be empty.
    std::string_view                    sTag;
};

An embeddings request.

class

CEmbedResult

Ethereal::Ai::Llm#

The vectors of an embeddings response, in the order of the inputs.

class CEmbedResult

Everything lives in the arena of the result, reset by every parse: reused for requests of the same size, it does not allocate once warm.

For the exclusive use of one thread.
constructor

CEmbedResult

#
explicit CEmbedResult( Memory::IAllocator * pAllocator = nullptr, const SLimits & Limits = {} ) noexcept;

An empty result. pAllocator null is Memory::DefaultAllocator.

function

Reset

#
void Reset( void ) noexcept;

Forgets the vectors, keeps the memory.

function

Count

#
ETL_UINT32 Count( void ) const noexcept

Number of vectors (the number of inputs).

function

Dimensions

#
ETL_UINT32 Dimensions( void ) const noexcept

Size of each vector.

function

Vector

#
std::span< const float > Vector( ETL_UINT32 uIndex ) const noexcept;

The vector of input uIndex, or empty when out of range.

function

Model

#
std::string_view Model( void ) const noexcept

The model that answered.

function

InputTokens

#
ETL_UINT64 InputTokens( void ) const noexcept

'usage.prompt_tokens'.

function

RequestId

#
std::string_view RequestId( void ) const noexcept

The id of the request ('x-request-id'). Filled by the transport.

function

Holder

#
CRequest & Holder( void ) noexcept

The request that holds the arena (and the texts of an error). Internal.

function

Set

#
void Set( const float * pData, ETL_UINT32 uCount, ETL_UINT32 uDimensions, std::string_view sModel, ETL_UINT64 uInputTokens ) noexcept;

Sets what ParseEmbedResponse read, or the id of the transport. Internal.

function

SetRequestId

#
void SetRequestId( std::string_view sId ) noexcept
function

WriteEmbedBody

Ethereal::Ai::Llm#
EStatus WriteEmbedBody( const SEmbedRequest & Request, const SProviderOptions & Options, std::span< char > Out, std::size_t & uSize ) noexcept;

Writes the body of the embeddings endpoint.

Request
The request.
Options
The provider: OpenAI or a compatible server.
Out
Destination. May be empty, to measure.
uSize
Bytes of the body. After eBufferTooSmall, the size needed.
eOk, eBufferTooSmall, eInvalidArgument (no model, no input, too many, an empty one, text that is not UTF-8), eUnsupported (Anthropic) or eNotLicensed.
function

ParseEmbedResponse

Ethereal::Ai::Llm#
EStatus ParseEmbedResponse( std::string_view sBody, CEmbedResult & Out, ETL_UINT32 uExpected = 0 ) noexcept;

Reads an embeddings response into Out, the vectors put in the order of their 'index'.

Every vector must have the same size, and the indexes must be 0 to n - 1, each once. With uExpected (the number of inputs), n must be it.

eOk, eMalformedResponse, eLimitExceeded (the limits of the result), eOutOfMemory or eNotLicensed.

llm_provider.hpp

#include <ethereal/cpp/ai/llm/llm_provider.hpp>

The provider adapters: writing the body of a request, reading a response that is not streamed, and reading an error.

One table of functions per provider, chosen once per call from SProviderOptions::eProvider. No network here: the transport (stage 3) sends what WriteRequestBody writes and hands the body it receives to ParseResponse or ParseError.

The body is written straight into the caller's buffer by Serialization::Json::CJsonWriter, without a tree or an intermediate string. A response is read by CJsonReader, only the fields the model needs, and the rest is skipped.

function

WriteRequestBody

Ethereal::Ai::Llm#
EStatus WriteRequestBody( CRequest & Request, const SProviderOptions & Options, bool bStream, std::span< char > Out, std::size_t & uSize ) noexcept;

Writes the JSON body of Request for the provider of Options.

The provider rules checked here: the Anthropic API takes the system messages apart and needs every one of them before the others, needs max_tokens, and refuses temperature, top_p and top_k from version 2026-10-21 on. OpenAI takes no top_k and no document as plain text. Reasoning blocks and cache marks are not written for OpenAI, which has no field for them.

Uses the scratch arena of the request (the data URL of an image for OpenAI, the members of the passthrough), reset at every call, so it does not allocate once the arena has grown.

Request
The request.
Options
The provider.
bStream
Asks for a streamed response.
Out
Destination. May be empty, to measure.
uSize
Bytes of the body. After eBufferTooSmall, the size needed.
eOk, eBufferTooSmall, the first error of the builder, eInvalidArgument (no model, no message, or a rule above), eUnsupported, eOutOfMemory or eNotLicensed.
function

ParseResponse

Ethereal::Ai::Llm#
EStatus ParseResponse( CRequest & Request, const SProviderOptions & Options, std::string_view sBody, SResponse & Out ) noexcept;

Reads the body of a successful response that was not streamed.

Resets the response arena of Request, and every text of Out points into it. Only the first choice of an OpenAI response is read (n = 1). Unknown fields and unknown block kinds (server tools, citations) are skipped.

eOk, eMalformedResponse, eLimitExceeded, eOutOfMemory or eNotLicensed.
function

ParseError

Ethereal::Ai::Llm#
EStatus ParseError( CRequest & Request, const SProviderOptions & Options, ETL_UINT32 uHttpStatus, std::string_view sBody, SError & Out ) noexcept;

Reads an HTTP error: the status gives the kind, the body refines it.

The body may be anything (an HTML page from a proxy, nothing): what it does not have stays empty, and the kind comes from the status alone. Resets the response arena of Request.

eOk (even when the body says nothing), eOutOfMemory or eNotLicensed.

llm_request.hpp

#include <ethereal/cpp/ai/llm/llm_request.hpp>

The data model of the Ai::Llm module: SBlock, SMessage, STool, SResponse, and CRequest, the builder of a request over an arena.

One model for every provider. CRequest holds what the caller adds, copied into its arena, and checks what can be checked without knowing the provider (roles, JSON of tool inputs and schemas, limits). What depends on the provider is checked when the body is written (llm_provider.hpp).

A CRequest has two arenas: one for the request and one for the response. Parsing a response resets only the second, so a request can be sent again (a retry) without being built again.

struct

SCheck

Ethereal::Ai::Llm#
C++
struct   SCheck
{
    /// @brief  The verdict.
    ECheck                        eResult = ECheck::eIncomplete;

    /// @brief  eJsonSyntax when the text is not JSON (eResult is eInvalid), eOk
    ///             otherwise. Error.pMessage and Error.uOffset then say what broke and
    ///             where.
    Schema::EStatus                eStatus = Schema::EStatus::eOk;

    /// @brief  With eInvalid, the first break: the keyword, the JSON Pointer in the
    ///             value, the static message. sDetail is a view into the CSchema, which
    ///             must outlive the response (the schemas of AddTool< T > live until the
    ///             end of the process).
    Schema::SValidationError    Error;
};

The verdict on the input of a tool use or on the structured output, against the schema the provider was given (CRequest::SetCheckMode).

struct

SSchemaSource

Ethereal::Ai::Llm#
C++
struct   SSchemaSource
{
    /// @brief  The text in a dialect (Schema::SchemaOf). Empty on lack of memory.
    std::string_view ( * pfnText )( Schema::EDialect eDialect ) noexcept = nullptr;

    /// @brief  That text compiled. Null on lack of memory.
    const Schema::CSchema * ( * pfnCompiled )( Schema::EDialect eDialect ) noexcept = nullptr;
};

The schema of a C++ type in every dialect, built and compiled on first use (kSchemaOf< T >). The dialect is chosen when the body is written, because a CRequest does not know its provider until then.

struct

SBlock

Ethereal::Ai::Llm#
C++
struct   SBlock
{
    /// @brief  The kind.
    EBlock                eType = EBlock::eText;

    /// @brief  Where the data of an image or document is.
    ESource                eSource = ESource::eBase64;

    /// @brief  Prompt caching mark.
    ECache                eCache = ECache::eNone;

    /// @brief  The tool result is an error.
    bool                bIsError = false;

    /// @brief  Text, reasoning, or the content of a tool result.
    std::string_view    sText;

    /// @brief  Base64, URL or plain text of an image or document. The data of a
    ///             redacted reasoning.
    std::string_view    sData;

    /// @brief  "image/png", "application/pdf".
    std::string_view    sMediaType;

    /// @brief  Title of a document.
    std::string_view    sTitle;

    /// @brief  Id of a tool use, or of the tool use a result answers.
    std::string_view    sId;

    /// @brief  Name of the tool of a tool use.
    std::string_view    sName;

    /// @brief  Input of a tool use: a JSON object, as text.
    std::string_view    sInput;

    /// @brief  Signature of a reasoning block.
    std::string_view    sSignature;

    /// @brief  The verdict on the input of a tool use of a response, against the schema
    ///             of its tool (CRequest::SetCheckMode). Null when it was not checked: the
    ///             mode is eOff, the tool has no schema to check with, or the block was
    ///             added by hand.
    const SCheck *        pCheck = nullptr;

    /// @brief  Next block of the message.
    const SBlock *        pNext = nullptr;
};

One content block.

Which fields a kind uses:

| Kind | Fields | |--------------------|-----------------------------------------------------| | eText | sText, eCache | | eImage | eSource (eBase64 or eUrl), sMediaType, sData, eCache | | eDocument | eSource, sMediaType, sData, sTitle, eCache | | eToolUse | sId, sName, sInput (a JSON object as text), pCheck | | eToolResult | sId (the tool use it answers), sText, bIsError, eCache | | eThinking | sText (the reasoning), sSignature | | eRedactedThinking | sData |

Text is UTF-8 and decoded (no JSON escapes). The views point into the arena of the request or of the response that holds the block.

struct

SMessage

Ethereal::Ai::Llm#
C++
struct   SMessage
{
    /// @brief  Who wrote it.
    ERole                eRole = ERole::eUser;

    /// @brief  Number of blocks.
    ETL_UINT32            uBlocks = 0;

    /// @brief  First block, or null.
    const SBlock *        pFirst = nullptr;

    /// @brief  Next message, or null.
    const SMessage *    pNext = nullptr;
};

One message: a role and its blocks.

struct

STool

Ethereal::Ai::Llm#
C++
struct   STool
{
    /// @brief  Name: 1 to 64 characters of a-z, A-Z, 0-9, '_' and '-' (the rule both
    ///             providers accept).
    std::string_view    sName;

    /// @brief  Description. May be empty.
    std::string_view    sDescription;

    /// @brief  The JSON Schema of the input: a JSON object, as text. For a tool of
    ///             AddTool< T >, the generic text (pSource gives the one that goes out).
    std::string_view    sSchema;

    /// @brief  The schema of a C++ type (AddTool< T >): the body carries it in the
    ///             dialect of the provider, and the input is checked against that text.
    ///             Null for a tool given as JSON.
    const SSchemaSource *    pSource = nullptr;

    /// @brief  For a tool given as JSON: the schema that checks the input of its tool
    ///             uses. Must outlive the request and its responses. May be null.
    const Schema::CSchema *    pCheck = nullptr;

    /// @brief  Asks the provider to follow the schema strictly ('strict': true).
    bool                bStrict = false;

    /// @brief  Prompt caching mark (Anthropic).
    ECache                eCache = ECache::eNone;

    /// @brief  Next tool, or null.
    const STool *        pNext = nullptr;
};

A tool the model may call, in the portable form. Written as an Anthropic tool or as an OpenAI function.

struct

SKeyValue

Ethereal::Ai::Llm#
C++
struct   SKeyValue
{
    std::string_view    sKey;
    std::string_view    sValue;
    const SKeyValue *    pNext = nullptr;
};

A key and value of the request metadata.

struct

SText

Ethereal::Ai::Llm#
C++
struct   SText
{
    std::string_view    sText;
    const SText *        pNext = nullptr;
};

A stop sequence.

struct

STimings

Ethereal::Ai::Llm#
C++
struct   STimings
{
    /// @brief  The connection was ready (TCP and TLS). Zero when a pooled
    ///             connection was reused.
    ETL_UINT64        uConnectNs = 0;

    /// @brief  The first byte of the response arrived.
    ETL_UINT64        uFirstByteNs = 0;

    /// @brief  The response ended.
    ETL_UINT64        uTotalNs = 0;
};

Times of a request, in nanoseconds since it started. Filled by the transport. Zero when not measured.

struct

SResponse

Ethereal::Ai::Llm#
C++
struct   SResponse
{
    /// @brief  First block, or null.
    const SBlock *        pFirst = nullptr;

    /// @brief  Number of blocks.
    ETL_UINT32            uBlocks = 0;

    /// @brief  Why the model stopped.
    EStopReason            eStopReason = EStopReason::eNone;

    /// @brief  The stop reason as the provider wrote it ("end_turn", "stop").
    std::string_view    sStopReason;

    /// @brief  The stop sequence that ended the output, when the provider says.
    std::string_view    sStopSequence;

    /// @brief  The refusal text of an OpenAI message. Empty otherwise.
    std::string_view    sRefusal;

    /// @brief  Id of the message or completion.
    std::string_view    sId;

    /// @brief  The model that answered.
    std::string_view    sModel;

    /// @brief  Id of the request ('request-id' or 'x-request-id' header). Filled by
    ///             the transport.
    std::string_view    sRequestId;

    /// @brief  The verdict on the structured output (the text blocks, as one document),
    ///             against the schema of SetOutputSchema. Null when it was not checked.
    const SCheck *        pOutputCheck = nullptr;

    /// @brief  Tokens.
    SUsage                Usage;

    /// @brief  Times. Filled by the transport.
    STimings            Timings;
};

A response of the model, the same for every provider.

The views point into the response arena of the request that parsed it, valid until the next parse with that request or until it is reset.

class

CRequest

Ethereal::Ai::Llm#

Builds a request over an arena.

class CRequest

Messages are added one at a time with AddMessage, and each block goes to the last message. Every text is copied into the arena. The first error is kept (Status): later calls still check their own arguments, and the body is not written while an error is kept.

Reset forgets everything and keeps the memory, so after the first requests a CRequest reused for the same kind of conversation does not allocate.

For the exclusive use of one thread.
constructor

CRequest

#
explicit CRequest( Memory::IAllocator * pAllocator = nullptr, const SLimits & Limits = {} ) noexcept;

An empty request.

pAllocator
Source of the memory of both arenas. Null is Memory::DefaultAllocator.
Limits
Limits of the request and of the responses parsed with it.
function

Reset

#
void Reset( void ) noexcept;

Forgets the request and the response, keeps the memory.

function

Status

#
EStatus Status( void ) const noexcept

The first error of the builder, or eOk.

function

SetModel

#
EStatus SetModel( std::string_view sModel ) noexcept;

The model ("claude-opus-5-5"). Required.

function

SetMaxTokens

#
EStatus SetMaxTokens( ETL_UINT32 uMaxTokens ) noexcept;

Maximum output tokens. Required by the Anthropic API, where 0 only warms the prompt cache.

function

SetTemperature

#
EStatus SetTemperature( ETL_DOUBLE dValue ) noexcept;

Temperature, from 0 to 2. Refused by the Anthropic API from version 2026-10-21 on (eUnsupported when the body is written).

function

SetTopP

#
EStatus SetTopP( ETL_DOUBLE dValue ) noexcept;

Nucleus sampling, from 0 to 1. Same note as SetTemperature.

function

SetTopK

#
EStatus SetTopK( ETL_UINT32 uValue ) noexcept;

Top-k sampling. Not taken by OpenAI, and refused by the Anthropic API from 2026-10-21 on. Servers compatible with OpenAI usually take it.

function

AddStopSequence

#
EStatus AddStopSequence( std::string_view sText ) noexcept;

One more stop sequence (OpenAI takes up to 4).

function

AddMetadata

#
EStatus AddMetadata( std::string_view sKey, std::string_view sValue ) noexcept;

One more metadata pair. The Anthropic API only knows "user_id".

function

AddMessage

#
EStatus AddMessage( ERole eRole ) noexcept;

Starts a message. The blocks added next go to it.

function

AddText

#
EStatus AddText( std::string_view sText, ECache eCache = ECache::eNone ) noexcept;

A text block.

function

AddImage

#
EStatus AddImage( ESource eSource, std::string_view sMediaType, std::string_view sData, ECache eCache = ECache::eNone ) noexcept;

An image (user messages). sMediaType is required for eBase64.

function

AddDocument

#
EStatus AddDocument( ESource eSource, std::string_view sMediaType, std::string_view sData, std::string_view sTitle = {}, ECache eCache = ECache::eNone ) noexcept;

A document (user messages). sMediaType is required for eBase64 and eText. sTitle may be empty.

function

AddToolUse

#
EStatus AddToolUse( std::string_view sId, std::string_view sName, std::string_view sInputJson ) noexcept;

A tool use (assistant messages). sInputJson must be a JSON object.

function

AddToolResult

#
EStatus AddToolResult( std::string_view sToolUseId, std::string_view sText, bool bIsError = false, ECache eCache = ECache::eNone ) noexcept;

A tool result (user and tool messages).

function

AddThinking

#
EStatus AddThinking( std::string_view sThinking, std::string_view sSignature ) noexcept;

A reasoning block, as the provider sent it (assistant messages).

function

AddRedactedThinking

#
EStatus AddRedactedThinking( std::string_view sData ) noexcept;

A redacted reasoning block, as the provider sent it (assistant messages).

function

AddResponse

#
EStatus AddResponse( const SResponse & Response ) noexcept;

Appends an assistant message with every block of Response, copied. The way to continue a conversation after a response (a tool call, a paused turn), with the reasoning blocks kept as they came.

function

AddTool

#
EStatus AddTool( std::string_view sName, std::string_view sDescription, std::string_view sSchemaJson, bool bStrict = false, ECache eCache = ECache::eNone, const Schema::CSchema * pCheck = nullptr ) noexcept;

One more tool, in the portable form. sSchemaJson must be a JSON object. pCheck, the same schema compiled, checks the input of the tool uses of the responses (SetCheckMode): it must outlive the request and its responses, and may be null.

function

AddTool

#
EStatus AddTool( std::string_view sName, std::string_view sDescription, const SSchemaSource & Source, bool bStrict = false, ECache eCache = ECache::eNone ) noexcept;

One more tool, with the schema of a C++ type. The body carries the schema in the dialect of the provider and of bStrict (ToolDialect), and the input of the tool uses is checked against that text.

function

AddTool

#
template < typename T > EStatus AddTool( const std::string_view sName, const std::string_view sDescription, const bool bStrict = false, const ECache eCache = ECache::eNone ) noexcept

One more tool whose input is the described type T.

function

SetToolsRaw

#
EStatus SetToolsRaw( std::string_view sJsonArray ) noexcept;

The 'tools' array as the provider takes it, written unchanged in place of the portable tools. For tools the portable form does not model (server tools, custom grammar). Must be a JSON array.

function

SetToolChoice

#
EStatus SetToolChoice( EToolChoice eChoice, std::string_view sName = {}, bool bDisableParallel = false ) noexcept;

Which tool the model may call. sName is required for eTool. bDisableParallel asks for at most one call.

function

SetOutputSchema

#
EStatus SetOutputSchema( std::string_view sName, std::string_view sSchemaJson, bool bStrict = true, const Schema::CSchema * pCheck = nullptr ) noexcept;

Structured output: the response must follow sSchemaJson (a JSON object). sName is required by OpenAI (up to 64 characters). pCheck, the same schema compiled, checks the output (SetCheckMode): it must outlive the request and its responses, and may be null.

function

SetOutputSchema

#
EStatus SetOutputSchema( std::string_view sName, const SSchemaSource & Source, bool bStrict = true ) noexcept;

Structured output with the schema of a C++ type, in the dialect of the provider (OutputDialect), checked against that text.

function

SetOutputSchema

#
template < typename T > EStatus SetOutputSchema( const std::string_view sName, const bool bStrict = true ) noexcept

Structured output of the described type T.

function

SetCheckMode

#
EStatus SetCheckMode( ECheckMode eMode ) noexcept;

What is done with the schemas when a response arrives. eReport by default. Kept by Reset.

function

SetUsageTag

#
EStatus SetUsageTag( std::string_view sTag ) noexcept;

The tag under which the client records the usage of this request (CUsageLedger): a feature, a customer, a job. May be empty. Cleared by Reset.

function

SetRawBody

#
EStatus SetRawBody( std::string_view sJsonObject ) noexcept;

The whole body, as the provider takes it: WriteRequestBody writes it unchanged in place of the one built from the request (stage 8, the raw JSON of the C layer). Must be a JSON object. The streaming flag goes in it ("stream": true): the client does not add it. The responses are read as usual, so the model and the limits of the request still apply to them.

function

SetPassthrough

#
EStatus SetPassthrough( std::string_view sJsonObject ) noexcept;

A JSON object whose members are merged into the body: a member with a name the module writes replaces it, the others are added. For features the module does not model yet ('thinking', 'service_tier').

function

Model

#
std::string_view Model( void ) const noexcept
function

HasMaxTokens

#
bool HasMaxTokens( void ) const noexcept
function

MaxTokens

#
ETL_UINT32 MaxTokens( void ) const noexcept
function

HasTemperature

#
bool HasTemperature( void ) const noexcept
function

Temperature

#
ETL_DOUBLE Temperature( void ) const noexcept
function

HasTopP

#
bool HasTopP( void ) const noexcept
function

TopP

#
ETL_DOUBLE TopP( void ) const noexcept
function

HasTopK

#
bool HasTopK( void ) const noexcept
function

TopK

#
ETL_UINT32 TopK( void ) const noexcept
function

StopSequences

#
const SText * StopSequences( void ) const noexcept
function

StopSequenceCount

#
ETL_UINT32 StopSequenceCount( void ) const noexcept
function

Metadata

#
const SKeyValue * Metadata( void ) const noexcept
function

Messages

#
const SMessage * Messages( void ) const noexcept
function

MessageCount

#
ETL_UINT32 MessageCount( void ) const noexcept
function

BlockCount

#
ETL_UINT32 BlockCount( void ) const noexcept
function

Tools

#
const STool * Tools( void ) const noexcept
function

ToolsRaw

#
std::string_view ToolsRaw( void ) const noexcept
function

ToolChoice

#
EToolChoice ToolChoice( void ) const noexcept
function

ToolChoiceName

#
std::string_view ToolChoiceName( void ) const noexcept
function

DisableParallelToolUse

#
bool DisableParallelToolUse( void ) const noexcept
function

OutputSchemaName

#
std::string_view OutputSchemaName( void ) const noexcept
function

OutputSchema

#
std::string_view OutputSchema( void ) const noexcept
function

OutputSchemaStrict

#
bool OutputSchemaStrict( void ) const noexcept
function

OutputSchemaSource

#
const SSchemaSource * OutputSchemaSource( void ) const noexcept
function

OutputSchemaCheck

#
const Schema::CSchema * OutputSchemaCheck( void ) const noexcept
function

CheckMode

#
ECheckMode CheckMode( void ) const noexcept
function

UsageTag

#
std::string_view UsageTag( void ) const noexcept
function

RawBody

#
std::string_view RawBody( void ) const noexcept
function

Passthrough

#
std::string_view Passthrough( void ) const noexcept
function

Limits

#
const SLimits & Limits( void ) const noexcept
function

Arena

#
CArena & Arena( void ) noexcept

The arena of the request.

function

ResponseArena

#
CArena & ResponseArena( void ) noexcept

The arena of the response, reset by every parse.

function

ScratchArena

#
CArena & ScratchArena( void ) noexcept

Scratch of WriteRequestBody, reset by every write.

function

CheckState

#
Detail::SCheckState * & CheckState( void ) noexcept

The validators of the checks, kept from one response to the next. Internal.

llm_stream.hpp

#include <ethereal/cpp/ai/llm/llm_stream.hpp>

CStreamDecoder: a streamed response of any provider, turned into the same events and the same SResponse.

The bytes of the response body (after the HTTP reader has taken off the framing and the gzip) go in by Feed, in slices of any size. Inside, the Http::CSseParser cuts the events, and a function per provider turns each one into the unified events below. The events go to a callback (a function pointer and a context), and the whole response is built at the same time, so the consumer can read it at any moment, and at the end it is the same SResponse ParseResponse gives for the same answer without streaming.

The same events come out for any slicing of the same bytes.

Formats read from the documentation of the providers on 13-11-2026.

enum

EStreamEvent

Ethereal::Ai::Llm#
C++
enum class   EStreamEvent : ETL_UINT8
{
    /// @brief  The message began. sId, sModel and pUsage (the input tokens).
    eMessageStart = 0,

    /// @brief  A block began. uIndex, eBlock, and for a tool use sId and sName. A
    ///             redacted reasoning comes whole here, its data in sText.
    eBlockStart,

    /// @brief  Text of a text block, in sText.
    eTextDelta,

    /// @brief  Reasoning of a thinking block, in sText.
    eThinkingDelta,

    /// @brief  A piece of the signature of a thinking block, in sText. Not in the
    ///             spec list: without it the block could not go back unchanged.
    eSignatureDelta,

    /// @brief  A piece of the input of a tool use, in sText: partial JSON, only whole
    ///             at the eBlockStop.
    eToolInputDelta,

    /// @brief  A piece of the refusal of an OpenAI message, in sText. Not in the spec
    ///             list: the refusal is not a block (SResponse::sRefusal).
    eRefusalDelta,

    /// @brief  A block ended. uIndex, and pBlock is the block complete.
    eBlockStop,

    /// @brief  The stop reason or the usage changed. eStopReason, pUsage (the
    ///             accumulated usage).
    eMessageDelta,

    /// @brief  The message ended. Nothing comes after.
    eMessageStop,

    /// @brief  A keep alive of the provider.
    ePing,

    /// @brief  The stream carried an error. pError.
    eError
};

The kind of a unified stream event.

function

StreamEventName

Ethereal::Ai::Llm#
const char * StreamEventName( EStreamEvent eKind ) noexcept;

Name of a stream event kind, for messages. Never returns null.

struct

SStreamEvent

Ethereal::Ai::Llm#
C++
struct   SStreamEvent
{
    /// @brief  What happened.
    EStreamEvent        eKind = EStreamEvent::ePing;

    /// @brief  The index of the block in the response (0, 1, 2), for the block events.
    ///             Blocks the module does not model are skipped and take no index.
    ETL_UINT32            uIndex = 0;

    /// @brief  The kind of the block, for the block events.
    EBlock                eBlock = EBlock::eText;

    /// @brief  The stop reason, for eMessageDelta. eNone while the provider did not
    ///             say.
    EStopReason            eStopReason = EStopReason::eNone;

    /// @brief  The delta, or the data of a redacted reasoning.
    std::string_view    sText;

    /// @brief  The id of the message (eMessageStart) or of the tool use (eBlockStart).
    std::string_view    sId;

    /// @brief  The name of the tool (eBlockStart of a tool use).
    std::string_view    sName;

    /// @brief  The model (eMessageStart).
    std::string_view    sModel;

    /// @brief  The block as built so far, for the block events.
    const SBlock *        pBlock = nullptr;

    /// @brief  The accumulated usage, for eMessageStart and eMessageDelta.
    const SUsage *        pUsage = nullptr;

    /// @brief  The error, for eError.
    const SError *        pError = nullptr;
};

A unified stream event.

The views and pointers are valid until the next call to Feed or Finish. The texts are decoded (no JSON escapes).

alias

void

Ethereal::Ai::Llm#
using PFN_OnStreamEvent = void ( * )( const SStreamEvent & Event, void * pUser );

Receives each event. pUser is the context given to Begin.

class

CStreamDecoder

Ethereal::Ai::Llm#

Decodes a streamed response.

class CStreamDecoder

The loop:

C++
Decoder.Begin( Request, Options, OnEvent, &Context );
while( the HTTP reader gives body data )
    if( Decoder.Feed( Data ) != EStatus::eOk ) break;
EStatus e = Decoder.Finish();
const SResponse & Response = Decoder.Response();

The response is built in the response arena of the request, so it lives until the next Begin, ParseResponse or ParseError with that request. The decoder keeps its own buffers between streams: reused, it does not allocate once warm, and neither does the arena.

For the exclusive use of one thread.
constructor

CStreamDecoder

#
explicit CStreamDecoder( Memory::IAllocator * pAllocator = nullptr ) noexcept;
pAllocator
Source of the buffers of the SSE parser and of the block table. Null is Memory::DefaultAllocator.
function

Begin

#
EStatus Begin( CRequest & Request, const SProviderOptions & Options, PFN_OnStreamEvent pfnOnEvent, void * pUser ) noexcept;

Starts a stream for Request. Resets its response arena.

Request
The request that was sent. Its limits apply, and the response is built in its arena.
Options
The provider.
pfnOnEvent
The callback. May be null: then the response is only built.
pUser
The context of the callback.
eOk, eInvalidArgument (a provider out of the table), eOutOfMemory (the validators of the checks) or eNotLicensed.
function

Feed

#
EStatus Feed( std::string_view sBytes ) noexcept;

Eats a slice of the body. Calls back for each event it completes.

eOk, or the cause of the failure: eMalformedResponse, eLimitExceeded, eOutOfMemory, eProviderError (the stream carried an error, after its eError event), eSchemaViolation (ECheckMode::eAbort: a tool input or the structured output can no longer follow its schema, after the event that showed it). A failure is sticky until Begin.
function

Finish

#
EStatus Finish( void ) noexcept;

The body ended. Checks the stream was complete.

An OpenAI stream that gave a finish reason and then ended without [DONE] is accepted, and gets its eMessageStop here (some compatible servers do not send [DONE]).

eOk, eTruncated, or the sticky failure.
function

Response

#
const SResponse & Response( void ) const noexcept

The response as built so far.

function

Error

#
const SError & Error( void ) const noexcept

The error the stream carried, after eProviderError.

function

Done

#
bool Done( void ) const noexcept

The message ended (eMessageStop went out).

function

Status

#
EStatus Status( void ) const noexcept

The sticky failure, or eOk.

function

Release

#
void Release( void ) noexcept;

Gives every buffer back. The decoder stays usable.

function

ReservedBytes

#
std::size_t ReservedBytes( void ) const noexcept

Bytes the decoder holds from its allocator (the SSE parser, the block table), without the response arena of the request (stage 7, L4).

struct

SGrow

#
C++
struct   SGrow
{
    char *            pData = nullptr;
    std::size_t        uSize = 0;
    std::size_t        uCapacity = 0;
};

A growing text in the response arena. Internal.

struct

SBuilder

#
C++
struct   SBuilder
{
    SBlock *        pBlock = nullptr;        /// Null for a block the module skips.
    SGrow            Main;                    /// Text, reasoning, input, or redacted data.
    SGrow            Second;                    /// The signature of a reasoning.
    SGrow            Id;                        /// OpenAI: the id of a tool call.
    SGrow            Name;                    /// OpenAI: the name of a tool call.
    ETL_UINT32        uIndex = 0;                /// The index in the response.
    Detail::SCheckLink    Check;                /// The check of a tool input (stage 5).
    bool            bOpen = false;
};

A block being built. Internal.

llm_tokenizer.hpp

#include <ethereal/cpp/ai/llm/llm_tokenizer.hpp>

Binds a tokenizer of AI-01 to the local count of the Llm module (CountTokensLocal) and to the token estimate of the rate limit (SRateLimits::pfnEstimate).

Header only and outside llm_inc.hpp: the Llm module does not need the tokenizer to be built. Include it where the program also builds Ai::Tokenizer (ETHEREAL_AI_TOKENIZER).

C++
Tokenizer::CTokenizer Tok;   /// o200k_base, loaded by the caller
Tokenizer::CWorkspace Work;  /// one per thread
Llm::STokenizerCounter Counter( Tok, Work );
Llm::SLocalCount Count;
Llm::CountTokensLocal( Request, &Llm::CountWithTokenizer, &Counter, {}, Count );
struct

STokenizerCounter

Ethereal::Ai::Llm#
C++
struct   STokenizerCounter
{
    STokenizerCounter( const Tokenizer::CTokenizer & Tok, Tokenizer::CWorkspace & Work ) noexcept
        : pTokenizer( &Tok ), pWork( &Work )
    {
        Options.eSpecialMode = Tokenizer::ESpecialMode::eTreatAsText;
    }

    const Tokenizer::CTokenizer *    pTokenizer = nullptr;
    Tokenizer::CWorkspace *            pWork = nullptr;
    Tokenizer::SEncodeOptions        Options;
};

The context of CountWithTokenizer: a tokenizer, the workspace of the calling thread, and the options of the count.

The special tokens are plain text by default (tiktoken encode_ordinary): a message that writes "<|endoftext|>" is text, as the provider sees it.

function

CountWithTokenizer

Ethereal::Ai::Llm#
inline bool CountWithTokenizer( void * const pUser, const std::string_view sText, ETL_UINT64 * const pTokens ) noexcept

PFN_CountText over STokenizerCounter.

llm_tokens.hpp

#include <ethereal/cpp/ai/llm/llm_tokens.hpp>

Counting tokens: through the counting endpoint of Anthropic (the body and the response, CClient::CountTokens), and locally, with a tokenizer the caller gives (CountTokensLocal).

Anthropic has no public tokenizer: its count comes from the API (POST /v1/messages/count_tokens, the same body as a message without the fields of generation). OpenAI and the compatible servers have no counting endpoint: their count is local, with the tokenizer of the model (AI-01, llm_tokenizer.hpp binds it).

The local count is the count of the texts of the request. How a provider frames each message in tokens is not documented, so it is not guessed: SLocalCountOptions takes the overhead per message, per tool and per request when the caller knows it.

function

WriteCountTokensBody

Ethereal::Ai::Llm#
EStatus WriteCountTokensBody( CRequest & Request, const SProviderOptions & Options, std::span< char > Out, std::size_t & uSize ) noexcept;

Writes the body of the counting endpoint of Anthropic: the body of WriteRequestBody without max_tokens, temperature, top_p, top_k, stop_sequences, metadata and stream, which its reference does not list.

The passthrough is merged as in WriteRequestBody: a field of generation put there by the caller goes out.

As WriteRequestBody, and eUnsupported for a provider other than Anthropic (OpenAI has no counting endpoint: count with CountTokensLocal).
function

ParseCountTokens

Ethereal::Ai::Llm#
EStatus ParseCountTokens( std::string_view sBody, ETL_UINT64 & uInputTokens ) noexcept;

Reads the response of the counting endpoint, {"input_tokens":N}.

eOk, eMalformedResponse (no input_tokens, or not a count) or eNotLicensed.
alias

bool

Ethereal::Ai::Llm#
using PFN_CountText = bool ( * )( void * pUser, std::string_view sText, ETL_UINT64 * pTokens ) noexcept;

Counts the tokens of one text into pTokens. False when it cannot (the text is refused by the tokenizer, no memory).

struct

SLocalCountOptions

Ethereal::Ai::Llm#
C++
struct   SLocalCountOptions
{
    /// @brief  Tokens added for each message (its role and its framing).
    ETL_UINT32        uPerMessage = 0;

    /// @brief  Tokens added for each portable tool.
    ETL_UINT32        uPerTool = 0;

    /// @brief  Tokens added once (the priming of the answer).
    ETL_UINT32        uPerRequest = 0;

    /// @brief  Counts the name, the description and the generic schema of each
    ///             portable tool, and the raw tools array.
    bool            bTools = true;

    /// @brief  Counts the schema of the structured output.
    bool            bOutputSchema = true;
};

What the local count adds besides the texts.

struct

SLocalCount

Ethereal::Ai::Llm#
C++
struct   SLocalCount
{
    /// @brief  Every token counted, the overheads included.
    ETL_UINT64        uTokens = 0;

    /// @brief  Texts given to the counter.
    ETL_UINT32        uTexts = 0;

    /// @brief  Blocks that have no text to count (images, documents other than plain
    ///             text, redacted reasoning): their tokens are not in uTokens.
    ETL_UINT32        uSkippedBlocks = 0;
};

The result of a local count.

function

CountTokensLocal

Ethereal::Ai::Llm#
EStatus CountTokensLocal( const CRequest & Request, PFN_CountText pfnCount, void * pUser, const SLocalCountOptions & Options, SLocalCount & Out ) noexcept;

Counts the tokens of the texts of Request with pfnCount.

Each text goes to the counter on its own: the system and message texts, the reasoning, the name and the input of each tool use, the content of each tool result, a document given as plain text, the tools (with bTools) and the output schema (with bOutputSchema). The sum is the count of the texts, plus the overheads of Options.

Request
The request.
pfnCount
The counter (llm_tokenizer.hpp binds a tokenizer of AI-01).
pUser
The context of the counter.
Options
The overheads and what is counted.
Out
Receives the count.
eOk, eInvalidArgument (no counter, or the counter refused a text), the error kept by the builder of the request, or eNotLicensed.

llm_types.hpp

#include <ethereal/cpp/ai/llm/llm_types.hpp>

Vocabulary of the Ai::Llm module: status, providers, roles, blocks, stop reasons, usage, limits, provider options and the provider error.

Everything that comes from a provider (a response, an error body, a stream) is untrusted input. Every limit has a safe default, and a hostile body gives an error, never a crash or a huge allocation.

The formats of the providers were read from their documentation on 13-11-2026.

enum

EStatus

Ethereal::Ai::Llm#
C++
enum class   EStatus : ETL_UINT32
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  An argument is null, empty, out of range, or not allowed where it was
    ///             given (a tool use in a user message, a block before any message).
    eInvalidArgument,

    /// @brief  The allocator returned null.
    eOutOfMemory,

    /// @brief  Refused: no license was accepted and the evaluation of this machine has
    ///             ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed,

    /// @brief  The caller's buffer is too small. The size needed is returned.
    eBufferTooSmall,

    /// @brief  More messages, blocks or bytes than SLimits allows.
    eLimitExceeded,

    /// @brief  The provider does not take what the request holds: a document as plain
    ///             text for OpenAI, top_k for OpenAI, temperature for the Anthropic API
    ///             from version 2026-10-21 on.
    eUnsupported,

    /// @brief  The body of a response is not JSON, or lacks a field the format
    ///             requires, or has one of the wrong type. In a stream, also an event out
    ///             of order (a delta of a block that was never started).
    eMalformedResponse,

    /// @brief  A stream carried an error event after the HTTP 200 (an overloaded
    ///             server, for one). CStreamDecoder::Error holds it.
    eProviderError,

    /// @brief  A stream ended before the provider said it was over (no message_stop,
    ///             no [DONE] and no finish reason).
    eTruncated,

    /// @brief  The connection failed: the name did not resolve, no address accepted it,
    ///             the TLS handshake or the TLS layer failed, or the connection broke.
    ///             SCallResult::Http has the cause (stage 3, CClient).
    eTransport,

    /// @brief  A time limit ran out. SCallResult::Http::eTimeout says which.
    eTimedOut,

    /// @brief  The request was cancelled: by the token, by CClient::Cancel, or by the
    ///             client closing.
    eCancelled,

    /// @brief  The rate limit of the client (or the one the provider announced in its
    ///             headers) would make the request wait longer than SRateLimits::uMaxWaitMs
    ///             (stage 4).
    eRateLimited,

    /// @brief  The circuit breaker of the client is open: the provider failed too often
    ///             lately, and the request was not sent (stage 4).
    eCircuitOpen,

    /// @brief  With ECheckMode::eAbort, the input of a tool use or the structured
    ///             output broke its schema. A stream stops at the first byte that
    ///             decides it. The block (SBlock::pCheck) or the response
    ///             (SResponse::pOutputCheck) says where (stage 5).
    eSchemaViolation
};

Result of an operation of the module.

function

StatusName

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

Name of a status, for messages. Never returns null.

enum

EProvider

Ethereal::Ai::Llm#
C++
enum class   EProvider : ETL_UINT8
{
    /// @brief  Anthropic Messages API.
    eAnthropic = 0,

    /// @brief  OpenAI Chat Completions.
    eOpenAi,

    /// @brief  A server that speaks the Chat Completions format (Ollama, llama.cpp
    ///             server, vLLM, LM Studio, OpenRouter). Differences are compatibility
    ///             flags (kCompat*), not new adapters.
    eOpenAiCompatible
};

The API a request is written for.

const

kCompatLegacyMaxTokens

Ethereal::Ai::Llm#
inline constexpr ETL_UINT32 kCompatLegacyMaxTokens = 0x01u;

Writes 'max_tokens' instead of 'max_completion_tokens'. For servers that only know the older name.

const

kCompatNoStreamOptions

Ethereal::Ai::Llm#
inline constexpr ETL_UINT32 kCompatNoStreamOptions = 0x02u;

Leaves 'stream_options' out of a streaming request. For servers that refuse the field (the usage of the stream is then missing).

const

kAnthropicVersion

Ethereal::Ai::Llm#
inline constexpr std::string_view kAnthropicVersion = "2026-10-21";

The Anthropic API version this module was written against, sent in the 'anthropic-version' header unless SProviderOptions says otherwise.

enum

ERole

Ethereal::Ai::Llm#
C++
enum class   ERole : ETL_UINT8
{
    /// @brief  Instructions. The Anthropic API takes them apart from the messages, so
    ///             for it every system message must come before the others.
    eSystem = 0,

    /// @brief  The user.
    eUser,

    /// @brief  The model.
    eAssistant,

    /// @brief  Results of tools. Sent as a user message to the Anthropic API and as one
    ///             'tool' message per result to the OpenAI API.
    eTool
};

Who wrote a message.

enum

EBlock

Ethereal::Ai::Llm#
C++
enum class   EBlock : ETL_UINT8
{
    /// @brief  Text.
    eText = 0,

    /// @brief  An image, as base64 or URL.
    eImage,

    /// @brief  A document: a PDF as base64 or URL, or plain text.
    eDocument,

    /// @brief  The model calls a tool (assistant messages).
    eToolUse,

    /// @brief  The result of a tool (user and tool messages).
    eToolResult,

    /// @brief  Reasoning of the model, with its signature, sent back exactly as it came
    ///             (Anthropic, assistant messages).
    eThinking,

    /// @brief  Reasoning the provider encrypted. Opaque, sent back exactly as it came.
    eRedactedThinking
};

The kind of a content block.

enum

ESource

Ethereal::Ai::Llm#
C++
enum class   ESource : ETL_UINT8
{
    /// @brief  SBlock::sData is base64, with SBlock::sMediaType.
    eBase64 = 0,

    /// @brief  SBlock::sData is a URL.
    eUrl,

    /// @brief  SBlock::sData is plain text (documents only, Anthropic only).
    eText
};

Where the data of an image or a document is.

enum

ECache

Ethereal::Ai::Llm#
C++
enum class   ECache : ETL_UINT8
{
    /// @brief  No mark.
    eNone = 0,

    /// @brief  {"type":"ephemeral"}: the default lifetime of the provider (5 minutes).
    eEphemeral,

    /// @brief  {"type":"ephemeral","ttl":"1h"}.
    eEphemeral1h
};

Prompt caching mark on a block or a tool (Anthropic 'cache_control'). The OpenAI API caches by itself and the mark is not written for it.

enum

EStopReason

Ethereal::Ai::Llm#
C++
enum class   EStopReason : ETL_UINT8
{
    /// @brief  Not known yet (start of a stream), or the response had none.
    eNone = 0,

    /// @brief  Natural end ('end_turn', 'stop').
    eEndTurn,

    /// @brief  The token limit ('max_tokens', 'length').
    eMaxTokens,

    /// @brief  A stop sequence ('stop_sequence'). OpenAI reports it as 'stop'.
    eStopSequence,

    /// @brief  The model called tools ('tool_use', 'tool_calls').
    eToolUse,

    /// @brief  The provider refused or filtered the output ('refusal',
    ///             'content_filter', or an OpenAI message with 'refusal').
    eRefusal,

    /// @brief  A long turn was paused ('pause_turn'): send the response back as it is
    ///             for the model to continue.
    ePauseTurn,

    /// @brief  The context window of the model was exceeded
    ///             ('model_context_window_exceeded').
    eContextWindow,

    /// @brief  Another value. SResponse::sStopReason has it.
    eOther
};

Why the model stopped, the same for every provider. The value the provider sent is kept in SResponse::sStopReason.

enum

EToolChoice

Ethereal::Ai::Llm#
C++
enum class   EToolChoice : ETL_UINT8
{
    /// @brief  Not written: the default of the provider.
    eDefault = 0,

    /// @brief  The model decides.
    eAuto,

    /// @brief  The model must call some tool (Anthropic 'any', OpenAI 'required').
    eAny,

    /// @brief  The model must not call tools.
    eNone,

    /// @brief  The model must call the named tool.
    eTool
};

Which tool the model may call.

enum

ECheckMode

Ethereal::Ai::Llm#
C++
enum class   ECheckMode : ETL_UINT8
{
    /// @brief  Nothing is checked.
    eOff = 0,

    /// @brief  The input of each tool use and the structured output are checked, and the
    ///             verdict goes to SBlock::pCheck and SResponse::pOutputCheck. The response
    ///             goes on whatever the verdict. The default.
    eReport,

    /// @brief  As eReport, and the first break stops the response with
    ///             eSchemaViolation. A stream stops at the byte that decides it, which
    ///             saves the output tokens of the rest.
    eAbort
};

What is done with the schemas of the tools and of the structured output when a response arrives (CRequest::SetCheckMode).

enum

ECheck

Ethereal::Ai::Llm#
C++
enum class   ECheck : ETL_UINT8
{
    /// @brief  The value is still arriving, or it ended before it was complete (a
    ///             stream cut short, the output limit of max_tokens).
    eIncomplete = 0,

    /// @brief  The value is complete and follows the schema.
    eValid,

    /// @brief  The value breaks the schema, or is not JSON.
    eInvalid
};

The verdict of a check.

struct

SUsage

Ethereal::Ai::Llm#
C++
struct   SUsage
{
    /// @brief  Input tokens neither read from the cache nor written to it.
    ETL_UINT64        uInputTokens = 0;

    /// @brief  Output tokens, reasoning included.
    ETL_UINT64        uOutputTokens = 0;

    /// @brief  Input tokens read from the prompt cache.
    ETL_UINT64        uCacheReadTokens = 0;

    /// @brief  Input tokens written to the prompt cache.
    ETL_UINT64        uCacheWriteTokens = 0;

    /// @brief  Output tokens spent on reasoning, when the provider says (part of
    ///             uOutputTokens).
    ETL_UINT64        uReasoningTokens = 0;

    /// @brief  Every input token.
    ETL_UINT64 TotalInput( void ) const ETL_NOEXCEPT { return uInputTokens + uCacheReadTokens + uCacheWriteTokens; }
};

Tokens of one response, the same for every provider.

The input is split in three parts that do not overlap. The Anthropic API reports them that way. For OpenAI, uInputTokens is 'prompt_tokens' minus the cached and the cache written tokens.

struct

SLimits

Ethereal::Ai::Llm#
C++
struct   SLimits
{
    /// @brief  Messages in a request (the Anthropic API takes up to 100 000).
    ETL_UINT32        uMaxMessages = 100000u;

    /// @brief  Blocks in a request or a response, every message counted.
    ETL_UINT32        uMaxBlocks = 200000u;

    /// @brief  Bytes of a response body.
    std::size_t        uMaxResponseBytes = std::size_t( 64u ) << 20;

    /// @brief  Nesting of a response body (a tool input nests inside it).
    ETL_UINT32        uMaxDepth = 128u;
};

Limits of a request and of a response. The defaults are safe for input from the network.

struct

SProviderOptions

Ethereal::Ai::Llm#
C++
struct   SProviderOptions
{
    /// @brief  The API.
    EProvider            eProvider = EProvider::eAnthropic;

    /// @brief  The 'anthropic-version' of the requests. Decides what the Anthropic
    ///             adapter accepts (temperature, top_p and top_k are refused from
    ///             2026-10-21 on). Dates compare as text (YYYY-MM-DD).
    std::string_view    sAnthropicVersion = kAnthropicVersion;

    /// @brief  kCompat* flags, for eOpenAiCompatible.
    ETL_UINT32            uCompat = 0;
};

For which API, and how, a request is written and a response read.

enum

EErrorKind

Ethereal::Ai::Llm#
C++
enum class   EErrorKind : ETL_UINT8
{
    /// @brief  No error.
    eNone = 0,

    /// @brief  The request is wrong (400, 'invalid_request_error').
    eInvalidRequest,

    /// @brief  The key is missing or wrong (401).
    eAuthentication,

    /// @brief  The key may not do this, or the region is not served (403).
    ePermission,

    /// @brief  Model or route not found (404).
    eNotFound,

    /// @brief  Conflict (409).
    eConflict,

    /// @brief  The request is too large (413).
    eRequestTooLarge,

    /// @brief  Too many requests or tokens for now (429): repeat after a while.
    eRateLimit,

    /// @brief  Quota, credit or spend limit reached (402, or a 429 that says so):
    ///             repeating does not help.
    eQuota,

    /// @brief  The provider failed (500, 502, 'api_error').
    eServer,

    /// @brief  The provider is overloaded (529, 503, 'overloaded_error').
    eOverloaded,

    /// @brief  Timeout of the provider (408, 504, 'timeout_error').
    eTimeout,

    /// @brief  Something else.
    eUnknown
};

What an HTTP error of a provider means, the same for every provider.

function

ErrorKindName

Ethereal::Ai::Llm#
const char * ErrorKindName( EErrorKind eKind ) noexcept;

Name of an error kind, for messages. Never returns null.

struct

SError

Ethereal::Ai::Llm#
C++
struct   SError
{
    /// @brief  What it means.
    EErrorKind            eKind = EErrorKind::eNone;

    /// @brief  The HTTP status.
    ETL_UINT32            uHttpStatus = 0;

    /// @brief  Repeating the same request may succeed (408, 429 that is not a quota,
    ///             500, 502, 503, 504, 529, 'overloaded_error', 'api_error',
    ///             'timeout_error').
    bool                bRetryable = false;

    /// @brief  'error.type' of the body ("rate_limit_error").
    std::string_view    sType;

    /// @brief  'error.code' (OpenAI) or 'error.details.error_code' (Anthropic).
    std::string_view    sCode;

    /// @brief  'error.message'.
    std::string_view    sMessage;

    /// @brief  'request_id' of the body (Anthropic). The header, read by the
    ///             transport, has the same value.
    std::string_view    sRequestId;
};

An HTTP error of a provider, read from its status and body.

The text fields are views into the response arena of the request (see CRequest), valid until the next parse with that request or until the request is reset. Every field is empty when the body did not have it.

llm_usage.hpp

#include <ethereal/cpp/ai/llm/llm_usage.hpp>

The accounting of usage: CUsageLedger, the tokens summed per model and per tag of the caller, and the cost from a price table the caller gives.

The module never holds a price. A price changes with the provider, the date and the contract, so the table is always the caller's (SPrice). The ledger only counts tokens.

CClient keeps a ledger of its own and records every response that carried usage (CClient::UsageEntries). SClientConfig can also point at a ledger shared by many clients.

const

kUsageKeyBytes

Ethereal::Ai::Llm#
inline constexpr std::size_t kUsageKeyBytes = 64u;

Bytes of the model and of the tag kept by an entry, the zero included. A longer one is cut at a UTF-8 boundary, and the cut text is the key.

struct

SUsageTotals

Ethereal::Ai::Llm#
C++
struct   SUsageTotals
{
    /// @brief  Responses that carried usage.
    ETL_UINT64        uRequests = 0;

    /// @brief  The fields of SUsage, summed. For embeddings, the input tokens.
    ETL_UINT64        uInputTokens = 0;
    ETL_UINT64        uOutputTokens = 0;
    ETL_UINT64        uCacheReadTokens = 0;
    ETL_UINT64        uCacheWriteTokens = 0;
    ETL_UINT64        uReasoningTokens = 0;

    /// @brief  Adds one response.
    void Add( const SUsage & Usage ) ETL_NOEXCEPT
    {
        ++uRequests;
        uInputTokens      += Usage.uInputTokens;
        uOutputTokens     += Usage.uOutputTokens;
        uCacheReadTokens  += Usage.uCacheReadTokens;
        uCacheWriteTokens += Usage.uCacheWriteTokens;
        uReasoningTokens  += Usage.uReasoningTokens;
    }

    /// @brief  Adds other totals.
    void Add( const SUsageTotals & o ) ETL_NOEXCEPT
    {
        uRequests         += o.uRequests;
        uInputTokens      += o.uInputTokens;
        uOutputTokens     += o.uOutputTokens;
        uCacheReadTokens  += o.uCacheReadTokens;
        uCacheWriteTokens += o.uCacheWriteTokens;
        uReasoningTokens  += o.uReasoningTokens;
    }
};

Tokens summed over many responses.

struct

SUsageEntry

Ethereal::Ai::Llm#
C++
struct   SUsageEntry
{
    /// @brief  The model, zero terminated.
    char            aModel[ kUsageKeyBytes ] = {};

    /// @brief  The tag of the caller (CRequest::SetUsageTag), zero terminated. Empty for
    ///             requests without one.
    char            aTag[ kUsageKeyBytes ] = {};

    SUsageTotals    Totals;
};

The totals of one model and one tag.

class

CUsageLedger

Ethereal::Ai::Llm#

Usage summed per model and per tag.

class CUsageLedger

Thread safe: many clients and threads may add to the same ledger. Adding a pair (model, tag) seen before does not allocate. A new pair allocates only when the table grows.

constructor

CUsageLedger

#
explicit CUsageLedger( Memory::IAllocator * pAllocator = nullptr ) noexcept;

An empty ledger. pAllocator null is Memory::DefaultAllocator.

function

Add

#
EStatus Add( std::string_view sModel, std::string_view sTag, const SUsage & Usage ) noexcept;

Adds one response of sModel under sTag.

eOk, eInvalidArgument (an empty model) or eOutOfMemory (the pair is new and the table could not grow: nothing is added).
function

Total

#
SUsageTotals Total( void ) const noexcept;

Everything summed.

function

ModelTotal

#
SUsageTotals ModelTotal( std::string_view sModel ) const noexcept;

The sum of every tag of one model (cut as the key is).

function

TagTotal

#
SUsageTotals TagTotal( std::string_view sTag ) const noexcept;

The sum of every model of one tag (cut as the key is).

function

Entries

#
std::size_t Entries( std::span< SUsageEntry > Out ) const noexcept;

Copies the entries, in the order the pairs were first seen.

Out
Destination. May be empty, to measure.
The number of entries in the ledger. Only min( it, Out.size() ) are written.
function

Reset

#
void Reset( void ) noexcept;

Forgets every entry, keeps the memory.

struct

SPrice

Ethereal::Ai::Llm#
C++
struct   SPrice
{
    /// @brief  The model ("claude-opus-5-5"), or a prefix of it with bPrefix.
    std::string_view    sModel;

    /// @brief  sModel matches every model that starts with it. FindPrice prefers an exact
    ///             match, then the longest prefix.
    bool                bPrefix = false;

    ETL_DOUBLE            dInputPerMTok = 0.0;
    ETL_DOUBLE            dOutputPerMTok = 0.0;
    ETL_DOUBLE            dCacheReadPerMTok = 0.0;
    ETL_DOUBLE            dCacheWritePerMTok = 0.0;
};

The price of a model, per million tokens, in the currency of the caller.

The reasoning tokens are part of the output tokens and have no price of their own. The input of an embedding is priced as input.

function

FindPrice

Ethereal::Ai::Llm#
const SPrice * FindPrice( std::span< const SPrice > Table, std::string_view sModel ) noexcept;

The price of sModel in Table: the exact match, or the longest prefix, or null.

function

CostOf

Ethereal::Ai::Llm#
ETL_DOUBLE CostOf( const SUsageTotals & Totals, const SPrice & Price ) noexcept;

The cost of Totals at Price.

struct

SCostReport

Ethereal::Ai::Llm#
C++
struct   SCostReport
{
    /// @brief  The sum of the entries that have a price.
    ETL_DOUBLE        dTotal = 0.0;

    /// @brief  Entries with a price and without one.
    ETL_UINT32        uPriced = 0;
    ETL_UINT32        uUnpriced = 0;

    /// @brief  Tokens of the entries without a price (input, output and cache), left out
    ///             of dTotal.
    ETL_UINT64        uUnpricedTokens = 0;
};

The cost of many entries.

function

CostOf

Ethereal::Ai::Llm#
SCostReport CostOf( std::span< const SUsageEntry > Entries, std::span< const SPrice > Table ) noexcept;

The cost of Entries with the prices of Table.