What it does
- One API for Anthropic, OpenAI and compatible servers
- Local or remote servers that speak the OpenAI API
- Streaming with no allocation per event
- Connection pool and smart retries
- Cost control
Measured
- One text event in the stream: 172 ns at p50 and 267 ns at p99 on Anthropic (MSVC), 162 and 200 ns on OpenAI
- A 50-message request (about 20 KB): 15.6 µs on Anthropic, 9.8 µs on OpenAI (MSVC)
- Memory of a call in flight, without the payload: 3,288 bytes
- Zero allocation per event and per request after warm-up
Known limits
- Anthropic Messages, OpenAI Chat Completions and OpenAI-compatible servers. No Gemini or other providers' own APIs, no batches, file upload or real-time audio
- The module's tests use a local test server and fixtures written from the providers' documentation. Run chat_basic with your own key to check a provider live
Native client for language model APIs (Ethereal::Ai::Llm): the Anthropic Messages API, OpenAI Chat Completions, and servers that speak the Chat Completions format (Ollama, llama.cpp server, vLLM, LM Studio, OpenRouter, local or remote). One request object is written for any of the three: the body for the chosen provider is produced when the request is sent. The response comes back whole or streamed, as the same normalized events for every provider. Retries, a circuit breaker and a rate limiter are built in. Tool inputs and structured outputs are checked against their JSON Schemas while they arrive. The module also counts tokens, requests embeddings and keeps a usage ledger.
The transport is the library's own HTTP/1.1 client (Ethereal::Http, part of the core build) over the library's TLS 1.3: connection pool, keep-alive, gzip, four time limits and cancellation. Nothing else to link.
The module is optional: -DETHEREAL_AI_LLM=ON (off by default). It requires -DETHEREAL_AI_SCHEMA=ON (Ai::Schema, the schemas of the tools and of the structured output), and CMake stops with the reason when it is missing. When disabled, none of it goes into the binary.
#include <ethereal/cpp/ai/llm/llm_inc.hpp>
namespace Llm = Ethereal::Ai::Llm;
static void OnEvent( const Llm::SStreamEvent & Event, void * )
{
if( Event.eKind == Llm::EStreamEvent::eTextDelta )
std::fwrite( Event.sText.data(), 1, Event.sText.size(), stdout );
}
Llm::SClientConfig Config;
Config.Provider.eProvider = Llm::EProvider::eAnthropic; // the key comes from ANTHROPIC_API_KEY
Llm::CClient Client( Config ); // one per provider, shared by threads
if( Client.Status() != Llm::EStatus::eOk ) // no key, bad base URL...
return 1;
Llm::CRequest Request; // one thread at a time, reusable
Request.SetModel( "claude-opus-5-5" );
Request.SetMaxTokens( 1024 );
Request.AddMessage( Llm::ERole::eUser );
Request.AddText( "What is the capital of Portugal?" );
Llm::SResponse Response;
Llm::SCallResult Result;
if( Client.Send( Request, Response, Result ) == Llm::EStatus::eOk )
for( const Llm::SBlock * p = Response.pFirst; p != nullptr; p = p->pNext )
if( p->eType == Llm::EBlock::eText )
std::printf( "%.*s\n", int( p->sText.size() ), p->sText.data() );
// The conversation goes on with the response and the next question, this time streamed.
Request.AddResponse( Response );
Request.AddMessage( Llm::ERole::eUser );
Request.AddText( "And of Spain?" );
Client.Stream( Request, &OnEvent, nullptr, Response, Result );Always include llm_inc.hpp: it brings in the entire module in the right order. The SDK ships a complete program, a terminal chat with streaming and the provider chosen on the command line, in examples/ai/chat_basic.cpp.
---
API keys
The key is never written in code in the examples. When SClientConfig::sApiKey is empty, the client reads an environment variable: ANTHROPIC_API_KEY for Anthropic, OPENAI_API_KEY for OpenAI, or the variable named in sApiKeyEnv. The shipped examples use ETL_COMPAT_API_KEY for a compatible server.
set ANTHROPIC_API_KEY=<your key> (Windows)
export ANTHROPIC_API_KEY=<your key> (Linux, macOS)The client copies the key into its own buffer and wipes it when the client is destroyed. It is sent only in the header the provider expects (x-api-key or Authorization: Bearer) and never appears in a result, an error text, a log line, a Telemetry span or a crash report header. A compatible server may run without a key, and then none is sent. Status() returns eInvalidArgument when Anthropic or OpenAI has no key.
---
The three providers
eAnthropic | eOpenAi | eOpenAiCompatible | |
|---|---|---|---|
Base URL when sBaseUrl is empty | https://api.anthropic.com | https://api.openai.com/v1 | required (for example http://127.0.0.1:11434/v1) |
| Path appended | /v1/messages | /chat/completions, /embeddings | same as OpenAI |
max_tokens | required | optional | optional |
| System messages | taken apart, all must come first | system message | same as OpenAI |
| Tools | Anthropic tools | function tools | same as OpenAI |
| Token count | CountTokens (the API endpoint) | CountTokensLocal | CountTokensLocal |
| Embeddings | no (eUnsupported) | Embed | Embed |
- Anthropic. The
anthropic-versionheader isSProviderOptions::sAnthropicVersion, by defaultkAnthropicVersion("2026-10-21", the API version the module was written against). From that version on the API no longer takestemperature,top_pandtop_k: a request that sets them fails witheUnsupportedwhen the body is written, before anything is sent. Beta and other extra headers (anthropic-beta) go inSClientConfig::Headers. - OpenAI. No
top_kand no plain-text document (eUnsupported). Reasoning blocks and cache marks are not written, since the API has no field for them. A streamed request asks for the usage at the end (stream_options.include_usage). - Compatible servers. The OpenAI protocol, with the known differences as flags in
SProviderOptions::uCompat:kCompatLegacyMaxTokenswritesmax_tokensinstead ofmax_completion_tokens, andkCompatNoStreamOptionsleavesstream_optionsout. For HTTPS with a private root, setSClientConfig::Http.pTrustStore. A streamed request answered with a whole JSON body is read as a normal response, and no event comes. An OpenAI stream that gave a finish reason and ended without[DONE]is accepted.
---
The API
| Piece | What it does |
|---|---|
CClient( Config ) / Status() | a client of one provider. Status() says whether it can send |
Send( Request, Response, Result ) | sends and reads the whole response |
Stream( Request, pfnOnEvent, pUser, Response, Result ) | sends for a streamed response, events on the calling thread, Response built at the same time |
StartAsync( Request, bStream, pfnOnEvent, pfnDone, pUser, &Id ) / Cancel( Id ) | asynchronous call, on a thread of the client (bAsyncOwnThread, the default) or on the caller's loop (RunAsync) |
CountTokens( Request, uTokens, Result ) | input tokens through the Anthropic counting endpoint |
Embed( SEmbedRequest, CEmbedResult, Result ) | embeddings (OpenAI and compatible servers), up to kEmbedMaxInputs (2,048) inputs |
UsageTotal() / UsageEntries( span ) / ResetUsage() | the usage this client recorded, by model and by tag |
Stats() / CallStateBytes() | transport counters, memory of one call (diagnostics) |
StatusName( e ) / ErrorKindName( k ) / StreamEventName( k ) | readable names, never null |
Send, Stream and CountTokens also take optional per-call Http::STimeouts and an Http::CCancelToken. SCallResult carries the status, the provider error (SError: eKind, uHttpStatus, bRetryable, sType, sCode, sMessage, sRequestId), the transport result of the last attempt, the number of attempts, the time spent waiting, and bContentDelivered.
The request (CRequest)
| Call | What it adds |
|---|---|
SetModel, SetMaxTokens, SetTemperature, SetTopP, SetTopK | parameters (see the provider notes) |
AddStopSequence, AddMetadata | stop sequences, metadata pairs |
AddMessage( ERole ) | starts a message (eSystem, eUser, eAssistant, eTool). Blocks go to the last message |
AddText, AddImage, AddDocument | content, with an optional cache mark (ECache::eEphemeral, eEphemeral1h) |
AddToolUse, AddToolResult | tool calls and their results |
AddThinking, AddRedactedThinking | reasoning blocks, sent back exactly as they came |
AddResponse( Response ) | appends the response as an assistant message, reasoning blocks intact |
AddTool( name, description, schemaJson ) / AddTool< T >( name, description ) | a tool, its schema as JSON or generated from a described C++ type |
SetToolChoice( EToolChoice, name, bDisableParallel ) | eAuto, eAny, eNone, eTool |
SetOutputSchema( name, schemaJson ) / SetOutputSchema< T >( name ) | structured output |
SetToolsRaw, SetPassthrough, SetRawBody | the provider's JSON written unchanged: the tools array, extra body members (thinking, service_tier), or the whole body |
SetCheckMode( ECheckMode ), SetUsageTag( tag ) | what is done with the schemas, the ledger tag |
Reset() | forgets the request and the response, keeps the memory |
Every text is copied into the request's arena. The first build error is kept (Status()), and every send with that request returns it until Reset().
The response
SResponse holds the blocks (pFirst, uBlocks), eStopReason (eEndTurn, eMaxTokens, eStopSequence, eToolUse, eRefusal, ePauseTurn, eContextWindow, eOther) with the provider's own text in sStopReason, sRefusal, sId, sModel, sRequestId, Usage and Timings. SUsage splits the input into three parts that do not overlap (uInputTokens, uCacheReadTokens, uCacheWriteTokens, summed by TotalInput()), plus uOutputTokens and uReasoningTokens.
Block (EBlock) | Fields of SBlock |
|---|---|
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, sText, bIsError, eCache |
eThinking | sText, sSignature |
eRedactedThinking | sData |
Streaming
SStreamEvent::eKind is one of eMessageStart, eBlockStart, eTextDelta, eThinkingDelta, eSignatureDelta, eToolInputDelta, eRefusalDelta, eBlockStop (with the complete block in pBlock), eMessageDelta (stop reason and accumulated usage), eMessageStop, ePing and eError. The events are the same whatever way the network slices the body. Texts are decoded (no JSON escapes) and valid until the callback returns. For a custom transport, CStreamDecoder (Begin, Feed, Finish) decodes a stream without the client, and WriteRequestBody, ParseResponse and ParseError do the same for whole bodies.
Schema checks
With ECheckMode::eReport (the default) each tool input and the structured output are validated as they arrive, and the verdict goes to SBlock::pCheck and SResponse::pOutputCheck (SCheck: eIncomplete, eValid or eInvalid, with the keyword and JSON Pointer of the first break). With eAbort the call stops with eSchemaViolation at the first byte that breaks the schema, which saves the output tokens of the rest. eOff checks nothing. FormatCheck writes a short English message for the model ("at /unit: ..."). DecodeToolInput< T > and DecodeOutput< T > decode straight into the described type, in the dialect the provider was given.
Tokens, usage and cost
CountTokensLocal( Request, pfnCount, pUser, SLocalCountOptions, SLocalCount )counts the texts of a request with any counter.llm_tokenizer.hpp(outsidellm_inc.hpp, needsETHEREAL_AI_TOKENIZER) binds an Ai::Tokenizer tokenizer:STokenizerCounterandCountWithTokenizer.CUsageLedgersums usage per model and per tag, thread safe.SClientConfig::pSharedUsagelets several clients add to one ledger.SPrice,FindPriceandCostOfturn the totals into a cost with the caller's price table. The module ships no prices.
---
Resilience and time limits
Setting (SClientConfig) | Default |
|---|---|
Retry.uMaxAttempts | 3 (the first included) |
Retry.uBaseDelayMs / uMaxDelayMs | 500 ms / 8,000 ms, exponential with full jitter |
Retry.uMaxRetryAfterMs | 60,000 ms. A longer retry-after returns the error |
Retry.uTotalBudgetMs | 0 (no limit) |
Retry.bRetryAfterContent | false |
RateLimits.uRequestsPerMinute / uTokensPerMinute | 0 (no limit) |
RateLimits.uMaxWaitMs | 60,000 ms, longer fails with eRateLimited |
RateLimits.bFollowServerHeaders | true |
bBreaker / Breaker | on, with a Resilience::SBreakerPolicy (see the [resilience module](resilience.md)) |
Timeouts.uConnectMs | 30,000 ms |
Timeouts.uFirstByteMs, uIdleMs, uTotalMs | 0 (no limit: a model can think for minutes before the first byte) |
Retried: connection failures, the connect time limit, a stream cut before its end, and provider errors marked bRetryable (408, 429 that is not a quota, 500, 502, 503, 504, 529, overloaded). Never retried: a request the provider refused for its content, a cancellation, a first-byte or idle time limit, or a stream that already handed content to the caller (unless bRetryAfterContent, and then the caller sees a new eMessageStart). The token estimate of the rate limit is the body size over four plus max_tokens, or RateLimits.pfnEstimate.
With SClientConfig::pTracer and a library built with ETHEREAL_TELEMETRY, each call opens one client span with the provider, operation, models, attempts, HTTP status, tokens and request id. Never the message content, never the key.
---
Limits and behavior
- Threads.
CClientis thread safe (Send,Stream,StartAsync,Cancel,Stats). ACRequestbelongs to one thread at a time and holds the last response in its arena. Response texts live until the next call with the same request orReset(). Different requests can run on the same client at the same time. - Memory. After warm-up, no allocation per request and none per stream event. The second request to the same host reuses the pooled connection, without a new handshake.
- Untrusted input. The provider's response is treated as untrusted.
SLimitscaps it (100,000 messages, 200,000 blocks, 64 MiB body, nesting 128 by default), and a hostile body is an error, never a crash. - Parsing. Only the first choice of an OpenAI response is read (n = 1). Unknown fields and block kinds (server tools, citations) are skipped.
- Not here: Gemini and other proprietary APIs, batch APIs, file upload, realtime audio.
---
C layer
Header ethereal/c/ai/llm.h. Four opaque handles (ETLC_LlmClient, ETLC_LlmRequest, ETLC_LlmCancel, ETLC_LlmEmbedResult), every function returns the ETLC_STATUS common to all C layers, and five module codes (ETLC_AI_PROVIDER_ERROR, ETLC_AI_CANCELLED, ETLC_AI_RATE_LIMITED, ETLC_AI_CIRCUIT_OPEN, ETLC_AI_SCHEMA_VIOLATION, -5806 to -5810) named by ETLC_StatusName. Every struct carries its size in the first field (iStructSize). The request is built by calls or given as raw JSON (ETLC_LlmRequestSetRawBody), the response is read block by block (ETLC_LlmRequestResponse, ETLC_LlmRequestBlock), and stream events reach a callback as a C struct.
ETLC_LlmClientConfig Config;
ETLC_LlmClient hClient = NULL;
ETLC_LlmRequest hRequest = NULL;
ETLC_LlmClientConfigDefault( &Config );
Config.iProvider = ETLC_LLM_PROVIDER_ANTHROPIC; /* the key comes from ANTHROPIC_API_KEY */
if( ETLC_LlmClientCreate( &Config, &hClient ) != ETLC_OK )
return 1;
ETLC_LlmRequestCreate( &hRequest );
ETLC_LlmRequestSetModel( hRequest, "claude-opus-5-5", ETLC_LLM_NUL_TERMINATED );
ETLC_LlmRequestSetMaxTokens( hRequest, 1024 );
ETLC_LlmRequestAddMessage( hRequest, ETLC_LLM_ROLE_USER );
ETLC_LlmRequestAddText( hRequest, "Hello!", ETLC_LLM_NUL_TERMINATED, ETLC_LLM_CACHE_NONE );
if( ETLC_LlmStream( hClient, hRequest, OnEvent, NULL, NULL, NULL ) == ETLC_OK )
ETLC_LlmRequestAddResponse( hRequest ); /* the conversation goes on */
ETLC_LlmRequestDestroy( hRequest );
ETLC_LlmClientDestroy( hClient );Also covered: ETLC_LlmSend, ETLC_LlmStartAsync and ETLC_LlmCancelAsync, cancellation tokens, ETLC_LlmCountTokens, ETLC_LlmEmbed and the client's usage totals (ETLC_LlmClientUsage). Differences from C++:
- The schemas of the tools and of the output are compiled by the request, so checks work from the schema text. A schema the validator does not accept is sent unchecked, not refused.
- The client trusts the system roots. Custom roots and client certificates stay on the C++ side.
- No local token count, no per-tag ledger, no price table and no Telemetry span.
The C layer is tested as C11 and C17 without extensions, and against the same local test server as the C++ side.
---
What was verified
- The module's tests run against a local HTTPS test server and against fixtures written from the providers' official documentation. Responses recorded from live traffic are not yet part of the fixtures.
- Streaming gives the same events, the same schema verdicts and the same final response under every slicing of the body tested, for Anthropic and OpenAI.
- The key does not appear in any result text, Telemetry span or crash report header, in every failure path tested.
- Clean on MSVC (Release and Debug), GCC, ASan and TSan. One hour of libFuzzer on responses, errors, checks, embeddings and the count (102.6 million executions) and one hour on the stream with the checks (10.7 million executions), with no finding.
Live provider tests are pending. No request to the real Anthropic or OpenAI API, or to a real compatible server, has been made by the vendor yet. The formats follow the providers' official documentation, and the compatibility flags cover the known differences. To try a provider with your own key, build examples/ai/chat_basic.cpp:
chat_basic anthropic [model]
chat_basic openai <model>
chat_basic compat http://127.0.0.1:11434/v1 <model>---
Performance
Intel Core i7-6700, one thread, Release builds.
| Measure | Target | MSVC | GCC |
|---|---|---|---|
| Text event in a stream, Anthropic (p50, p99) | 200 ns, 1 µs | 172 ns, 267 ns | 111 ns, 288 ns |
| Text event in a stream, OpenAI (p50, p99) | 200 ns, 1 µs | 162 ns, 200 ns | 102 ns, 134 ns |
| Request of 50 messages (about 20 KB), Anthropic and OpenAI | 20 µs | 15.6 and 9.8 µs | 10.7 and 8.0 µs |
| Memory of one call in progress, without the payload | 16 KB | 3,288 bytes | 3,288 bytes |
All targets are met. Zero allocations per event and per request after warm-up.