Expand description
aimux-ffi: C ABI for multi-language bindings.
Provides an opaque handle registry + JSON wire format + push callback
stream. The C ABI is consumed by C/C++, Go, Kotlin, Java, Swift, and
Flutter. Native bindings (Python / Node) bypass this layer and use
aimux-providers directly.
§Errors
Every fallible C function returns *mut aimux_error_t: NULL on
success (the result is written to the out-parameter), a heap-owned error
value on failure (the out-parameter is left at its sentinel: handle 0,
pointer NULL). Every non-NULL error has one code from aimux_error_code
and one message from aimux_error_message, and is released exactly once
with aimux_error_free. Codes 1..17 come from AiMuxError, 100..105
from RecordingError, and 200..206 identify failures detected while
crossing the C ABI.
§Memory ownership
- Every function returning
*mut c_char— error getters included — transfers ownership to the caller, who MUST free it withaimux_free_string. Handles (u64) are released withaimux_drop_handle. aimux_stream_textcallbacks receive*const c_charpointers that are valid only for the duration of the callback. The callback must copy the data synchronously; the backing buffer is freed when the callback returns.
§Concurrency
All async provider work runs on a shared multi-threaded tokio runtime. The
C ABI functions are synchronous: they block_on the runtime until the
operation completes. Callbacks execute on the same thread/call-stack that
invoked the FFI function, so they must not re-enter the FFI layer:
a nested block_on on the same thread makes tokio panic (“Cannot start
a runtime from within a runtime”). Rust’s non-unwind extern "C" ABI does
not allow a panic to propagate — the process terminates (and under this
workspace’s release profile, panic = "abort", it terminates at the panic
site). Either way the re-entrant call must be rejected before it reaches
the runtime; the thread-local guard in ffi_block_on does that
(issue M7).
Structs§
- aimux_
error_ t - The owned error returned by a failed C ABI invocation. Opaque to C: read it
with the
aimux_error_*getters, then release it once withaimux_error_free.
Constants§
- AIMUX_
E_ ABORTED - AIMUX_
E_ API_ CALL - AIMUX_
E_ FFI_ CALLBACK_ FAILURE - AIMUX_
E_ FFI_ INVALID_ HANDLE - AIMUX_
E_ FFI_ INVALID_ UTF8 - AIMUX_
E_ FFI_ INVALID_ WIRE_ JSON - AIMUX_
E_ FFI_ NULL_ POINTER - AIMUX_
E_ FFI_ REENTRANT_ CALL - AIMUX_
E_ FFI_ RESULT_ SERIALIZATION - AIMUX_
E_ INVALID_ ARGUMENT - AIMUX_
E_ INVALID_ PROMPT - AIMUX_
E_ INVALID_ RESPONSE_ DATA - AIMUX_
E_ INVALID_ TOOL_ INPUT - AIMUX_
E_ JSON_ PARSE - AIMUX_
E_ NO_ SUCH_ MODEL - AIMUX_
E_ NO_ SUCH_ PROVIDER - AIMUX_
E_ NO_ SUCH_ TOOL - AIMUX_
E_ OTHER - AIMUX_
E_ RECORDING_ FLUSH_ TIMEOUT - AIMUX_
E_ RECORDING_ INIT - AIMUX_
E_ RECORDING_ OPEN_ FILE - AIMUX_
E_ RECORDING_ SPAWN - AIMUX_
E_ RECORDING_ WRITE - AIMUX_
E_ RECORDING_ WRITER_ GONE - AIMUX_
E_ RETRY - AIMUX_
E_ TIMEOUT - AIMUX_
E_ TOKEN_ EXPIRED - AIMUX_
E_ TOOL_ CALL_ REPAIR - AIMUX_
E_ UNSUPPORTED_ FUNCTIONALITY - AIMUX_
OK - AIMUX_
TRANSCRIPTION_ NEXT_ PART_ ENDED - AIMUX_
TRANSCRIPTION_ NEXT_ PART_ PART - AIMUX_
TRANSCRIPTION_ NEXT_ PART_ TIMEOUT
Functions§
- aimux_
abort_ signal_ abort - Request cancellation for an abort-signal handle.
- aimux_
abort_ signal_ drop - Release an abort-signal handle.
- aimux_
abort_ signal_ new - Create a per-call abort signal for a cancelable FFI operation.
- aimux_
anthropic_ aws_ new - Create an Anthropic-on-AWS model instance (API key + region).
- aimux_
anthropic_ aws_ new_ with_ base - Create an Anthropic-on-AWS model instance with a custom base URL.
- aimux_
anthropic_ new - Create an Anthropic model instance. AiMuxError: invalid model id.
- aimux_
anthropic_ new_ with_ base - Create an Anthropic model instance with a custom base URL.
- aimux_
apply_ tool_ call_ repair - Resolve one invalid tool call against a host’s repair reply (RFC-0035).
- aimux_
apply_ tool_ call_ repair_ to_ result - Apply a repair reply to a whole result document (RFC-0035).
- aimux_
azure_ new - Create an Azure OpenAI model instance (API key + resource name).
- aimux_
azure_ new_ with_ base - Create an Azure OpenAI model instance with a custom base URL (required,
in place of
resource_name). - aimux_
bedrock_ new - Create a Bedrock model instance (AWS SigV4 credentials).
- aimux_
bedrock_ new_ with_ base - Create a Bedrock model instance with a custom base URL.
- aimux_
codex_ refresh - Refresh a Codex subscription access token (RFC-0018 §3.2).
- aimux_
cohere_ embedding_ new - aimux_
cohere_ embedding_ new_ with_ base - aimux_
cohere_ new - Create a Cohere model instance. AiMuxError: invalid model id.
- aimux_
cohere_ new_ with_ base - Create a Cohere model instance with a custom base URL.
- aimux_
cohere_ reranking_ new - Create a Cohere reranking model instance.
- aimux_
cohere_ reranking_ new_ with_ base - aimux_
consume_ stream_ text - Consume a stream to completion and write the aggregated result (M11, RFC-0016). Synchronous — blocks until the stream finishes.
- aimux_
drop_ handle - Release a handle previously returned by
aimux_*_new(any handle type — a transcription session’s driver task is aborted and joined as well, soaimux_transcription_session_dropis only a clearer name for the same thing). - aimux_
embed - Generate embeddings.
values_jsonis a JSON array of strings. WritesEmbeddingResultJSON (caller frees). - aimux_
error_ available_ tools AIMUX_E_NO_SUCH_TOOL: the available tool names as a JSON string array, or NULL when no tool set was supplied.- aimux_
error_ code - Machine-readable code (
aimux_error_code_t);AIMUX_OKfor NULL. - aimux_
error_ free - Release a returned error. NULL-safe; call exactly once.
- aimux_
error_ message - Human-readable description for every code; NULL only for NULL.
- aimux_
error_ model_ id AIMUX_E_NO_SUCH_MODEL: the model id that was asked for.- aimux_
error_ model_ type AIMUX_E_NO_SUCH_MODEL: the model type it was asked for as.- aimux_
error_ original_ error AIMUX_E_TOOL_CALL_REPAIR: the original lookup/parse/validation error as externally-tagged wire JSON — the same encoding asToolCall.error.- aimux_
error_ provider_ code AIMUX_E_API_CALL: the provider’s own error code, e.g. “insufficient_quota”.- aimux_
error_ provider_ data AIMUX_E_API_CALL: parsed provider error data as a JSON string.- aimux_
error_ provider_ id AIMUX_E_NO_SUCH_PROVIDER: the provider id that was asked for.- aimux_
error_ provider_ message AIMUX_E_API_CALL: the failure’s own text (“slow down”), without the composed prefixmessagecarries (“API call error: HTTP 429: slow down”).- aimux_
error_ request_ body_ values AIMUX_E_API_CALL: sanitized request body values as a JSON string; NULL when the request carried none (JSONnull).- aimux_
error_ response_ body AIMUX_E_API_CALL: raw response body.- aimux_
error_ response_ headers AIMUX_E_API_CALL: sanitized response headers as one JSON object string of name → value pairs, e.g.{"retry-after-ms":"1500"}.- aimux_
error_ retry_ count AIMUX_E_RETRY: number of recorded attempt errors; 0 under any other code or for NULL.- aimux_
error_ retry_ error_ at AIMUX_E_RETRY: the attempt error atindex(0-based, oldest first; the last entry is the final attempt) as a NEW owned error the caller reads with these same getters and releases withaimux_error_free, independently of the parent. NULL whenindexis out of range or under any other code.- aimux_
error_ retry_ ms AIMUX_E_API_CALL: retry hint in ms (0 = retry now), or -1 when none.- aimux_
error_ retry_ reason AIMUX_E_RETRY: why retrying stopped — the wire name ofRetryErrorReason: “maxRetriesExceeded” or “errorNotRetryable”.- aimux_
error_ retryable - 1 when retrying may help, 0 when it will not — the core’s verdict. Do not
infer it from
status: a statuslessAIMUX_E_API_CALLmay be either. - aimux_
error_ status - HTTP status: the observed status under
AIMUX_E_API_CALL, 401 by definition underAIMUX_E_TOKEN_EXPIRED, -1 otherwise or when no response was observed (AiMuxError::status_code). - aimux_
error_ tool_ input AIMUX_E_INVALID_TOOL_INPUT/AIMUX_E_NO_SUCH_TOOL: the raw argument text the model produced, or NULL when unavailable.- aimux_
error_ tool_ name AIMUX_E_NO_SUCH_TOOL/AIMUX_E_INVALID_TOOL_INPUT: the tool name the model called.- aimux_
error_ url AIMUX_E_API_CALL: sanitized request URL.- aimux_
file_ upload - aimux_
free_ ⚠string - Free a C string previously returned by any aimux function that hands out
*mut c_char— result JSON, error getters. - aimux_
generate_ object - Generate a structured JSON object from the model (M12, RFC-0016).
- aimux_
generate_ text - Non-streaming generation.
- aimux_
generate_ text_ as_ openai - Non-streaming text generation with OpenAI Chat Completions output.
- aimux_
generate_ text_ result_ as_ openai - Convert a serialized
GenerateTextResultinto a serializedChatCompletion. - aimux_
get_ model_ specs - Fetch the community model catalogue (anya2a). Writes a JSON-serialized
Catalogue(provider → model_id → ModelSpec). - aimux_
google_ embedding_ new - aimux_
google_ embedding_ new_ with_ base - aimux_
google_ image_ new - aimux_
google_ image_ new_ with_ base - aimux_
google_ video_ new - Create a Google video model instance.
- aimux_
google_ video_ new_ with_ base - aimux_
image_ generate - aimux_
init_ logging - Initialize the global logger. Idempotent — safe to call any number of times from any thread; only the first call has an effect.
- aimux_
init_ proxy - Set the global proxy configuration (M6, RFC-0016). Must be called before
the first
aimux_generate_text/aimux_stream_textcall; a no-op if the shared HTTP client is already initialised. - aimux_
init_ recording - Start recording (RFC-0023 P1/P2): writes complete
RecordingJSONL to{dir}/recordings.jsonl(dir auto-created). Recording is opt-in. Calling again with a different dir replaces the recorder. - aimux_
init_ recording_ ring - Start in-memory bounded recording (RFC-0023 P6):
RingRecorderwithcapentries, FIFO eviction, dropped-count queryable.cap == 0isAiMuxError::InvalidArgument. - aimux_
init_ recording_ ring_ default - No-argument variant of
aimux_init_recording_ring: initialize the global recorder with aRingRecorderat the library default capacity (2048 entries,aimux_core::recording::RingRecorder::default). Ordinary callers should prefer this entry point and leave the ring size to the library; pass an explicitcapviaaimux_init_recording_ringonly when a different size is required. - aimux_
list_ sessions - Query: all known sessions (RFC-0024). Writes a serialized
SessionView[]. - aimux_
mistral_ new - Create a Mistral model instance. AiMuxError: invalid model id.
- aimux_
mistral_ new_ with_ base - Create a Mistral model instance with a custom base URL.
- aimux_
moa_ new - Create a
MoaModel(RFC-0022) over the given reference handles + one aggregator handle. The new handle is a model handle (works withaimux_generate_text/aimux_stream_text); free it withaimux_drop_handle. - aimux_
mock_ replay_ new - Create a mock replay model from recorded JSONL (RFC-0023 P3).
recordingsis oneRecordingJSON per line. The handle works withaimux_generate_text/aimux_stream_text(no real API is sent). - aimux_
openai_ embedding_ new - Create an OpenAI embedding model instance.
- aimux_
openai_ embedding_ new_ with_ base - aimux_
openai_ files_ new - aimux_
openai_ files_ new_ with_ base - aimux_
openai_ image_ new - aimux_
openai_ image_ new_ with_ base - aimux_
openai_ new - Create an OpenAI model instance. AiMuxError: invalid model id.
- aimux_
openai_ new_ with_ base - Create an OpenAI model instance with a custom base URL.
- aimux_
openai_ speech_ new - aimux_
openai_ speech_ new_ with_ base - aimux_
openai_ transcription_ new - aimux_
openai_ transcription_ new_ with_ base - aimux_
provider_ from_ env - Convenience: create a language model by provider name, reading the API key from the provider’s env var.
- aimux_
provider_ handle_ new - Create a provider handle (RFC-0027) for a registry-backed provider.
- aimux_
provider_ list_ models - List models on a provider handle (RFC-0027 runtime discovery).
- aimux_
provider_ model - Build a language model from a provider handle + model_id (RFC-0027).
- aimux_
provider_ new - Create a language model from the registry by provider name (RFC-0017 phase 4).
- aimux_
recording_ flush - Flush the global recorder (blocks until JSONL is on disk; no-op for the
ring recorder). Write failures are not reported here — see
aimux_recording_try_flush. - aimux_
recording_ stop - Stop recording: global recorder = None (new calls are unrecorded).
- aimux_
recording_ try_ flush - Flush the global recorder and report write failures (see #136).
- aimux_
register_ providers - Register external OpenAI-compatible providers from a JSON config string
(RFC-0020).
config_jsonis{ "providers": [ { "name": ..., "base_url": ..., ... }, ... ] }. Entries override same-named built-ins or add new ones. Malformed JSON text isInvalidWireJson; a well-formed document the registry rejects isAiMuxError::InvalidArgument. - aimux_
rerank - Rerank documents.
opts_jsonis JSON-serializedRerankingCallOptions(must containqueryanddocuments). WritesRerankingResultJSON. - aimux_
router_ new - Create a
RouterModel(RFC-0021) over the given child-model handles. The new handle is itself a model handle (works withaimux_generate_text/aimux_stream_text); free it withaimux_drop_handle. - aimux_
search - Execute a search.
opts_jsonis JSON-serializedSearchCallOptions(must containquery). WritesSearchResultJSON. - aimux_
session_ calls - Query: all calls of a session, ordered by step (RFC-0024).
- aimux_
session_ infer_ init - Enable/disable the global session inferer (RFC-0024, opt-in, off by
default). Explicit
session_idvalues always win regardless.enablednonzero = on. - aimux_
session_ store_ init - Register the global session store (RFC-0024). Replaces any previous one. Until called, calls are not grouped and the session query functions return empty results.
- aimux_
speech_ generate - aimux_
stream_ text - Streaming generation with push callbacks.
- aimux_
stream_ text_ as_ openai - Streaming text generation with OpenAI Chat Completions output.
- aimux_
stream_ text_ as_ openai_ with_ abort - Cancelable streaming OpenAI-compatible output (see
aimux_stream_text_with_abort). - aimux_
stream_ text_ with_ abort - Stream text with a per-call abort signal.
- aimux_
tavily_ search_ new - Create a Tavily search model instance.
model_idis accepted for API symmetry but ignored (Tavily uses a fixed endpoint). - aimux_
tavily_ search_ new_ with_ base - aimux_
tool_ call_ repair_ context - Build the repair argument for one invalid tool call (RFC-0035).
- aimux_
trace_ aggregate - Query: aggregated probe statistics, filtered by
filter_json(a serializedTraceFilter; pass"{}"for all rows — NULL isNullPointer). Writes JSONTraceStats[]; caller frees withaimux_free_string. - aimux_
trace_ clear - Clear all probe records of a trace handle. Fails only for a dead handle.
- aimux_
trace_ export_ jsonl - Export all probe records as JSONL (one
TraceRecordper line). Writes a string with embedded newlines; caller frees withaimux_free_string. - aimux_
trace_ new - Wrap a model handle in a probe layer (RFC-0015). The new handle can be
used with
aimux_generate_text/aimux_stream_text(probed) and with theaimux_trace_*query functions; release withaimux_drop_handle. - aimux_
trace_ new_ audited - Wrap a model handle in a probe layer WITH the built-in rules auditor
(RFC-0015 §4).
strictnonzero = strict mode (self-hosted single instance); zero = shared mode (safe default). Release withaimux_drop_handle. - aimux_
trace_ session_ chain - Query: one session’s chain view. Writes JSON
SessionChainView; caller frees withaimux_free_string. An unknownsession_idis a lookup miss on a caller-supplied value and is reported asAiMuxError::InvalidArgument(“unknown session”), not as an invalid C handle — the id is a string key, not a registry handle. - aimux_
trace_ session_ trajectory - Query: one session’s per-step cache-hit trajectory (RFC-0024 §4.3).
Writes a JSON array of
SessionStepStat(empty for unknown sessions); caller frees withaimux_free_string. - aimux_
transcription_ generate - aimux_
transcription_ input_ done - Signal end-of-audio (the audio stream ends; the provider flushes). Safe to call multiple times. Fails only for a dead session handle.
- aimux_
transcription_ next_ part - Pull the next transcription part (JSON-serialized
TranscriptionStreamPart; free withaimux_free_string). - aimux_
transcription_ push_ audio - Push one binary audio chunk into the session. Blocking: waits while the internal channel is full (backpressure propagation; the caller’s capture loop throttles). Must not be called from within an aimux callback (re-entrancy guard rejects it).
- aimux_
transcription_ session_ drop - Terminate a transcription session and release it: aborts the driver, joins (bounded), and drops the handle. Safe with 0 or an unknown handle.
- aimux_
transcription_ session_ new - Start a transcription streaming session (RFC-0028 Phase 2). Internally
spawns the driver task immediately; audio is then pushed with
aimux_transcription_push_audioand parts pulled withaimux_transcription_next_part. - aimux_
vertex_ new - Create a Vertex AI model instance (GCP bearer token).
- aimux_
vertex_ new_ with_ base - Create a Vertex AI model instance with a custom base URL.
- aimux_
video_ generate - Generate video.
opts_jsonis JSON-serializedVideoCallOptions(must containprompt). WritesVideoResultJSON. - aimux_
xai_ new - Create an xAI model instance. AiMuxError: invalid model id.
- aimux_
xai_ new_ with_ base - Create an xAI model instance with a custom base URL.