mlxcel ships a pure-Python client that drives the OpenAI-compatible server (mlxcel serve) from Python. It either spawns and supervises a local server process (managed mode) or connects to an already-running one (connect mode), auto-discovers the served model id, and exposes the raw openai client for the full API surface (tools, response_format, logprobs, multimodal).
This is Phase 1 of Python integration. It builds entirely on the existing HTTP server: no native extension, and no changes to the Rust inference core. The package lives in python/ and is published under the import name mlxcel.
pip install ./python # from a repo checkout
pip install "./python[dev]" # adds pytest, ruff, mypyRequires Python 3.11 or newer. Runtime dependencies are openai>=1.40, httpx>=0.27, and platformdirs>=4.0. Managed mode additionally needs the mlxcel engine binary. The wheel does not carry one (a Linux CUDA build is hundreds of megabytes, past PyPI's per-file limit), so the client provisions it on demand — see Getting the engine binary.
Managed mode needs an mlxcel executable. The client resolves it in this order and stops at the first hit:
binary=passed toLLM/AsyncLLM.- The
MLXCEL_BINenvironment variable. mlxcelonPATH(for example a Homebrew install).- A previously provisioned download in the cache, for the pinned release (a cache entry for some other version is only picked up when you ask for that version).
- An on-demand download of the pinned release — only when nothing above exists.
So an engine you installed yourself always wins; the download is a fallback for when there is none.
On macOS arm64 or Linux, the first managed-mode use with no installed binary downloads the release asset for this platform, verifies its sha256 against the published .sha256, extracts the executable into a per-version cache, and runs it:
import mlxcel
# No mlxcel on PATH: prints a download line, then runs.
with mlxcel.LLM("mlx-community/Qwen3-4B-4bit") as llm:
print(llm.generate("hello"))To pre-fetch without loading a model (CI, air-gapped staging, the first run of a deployment):
python -m mlxcel install # pinned release
python -m mlxcel install --version 0.8.1
python -m mlxcel install --force # re-download over the cache
python -m mlxcel install -v # log the provisioning steps (cache hits stay at DEBUG)The Python form is mlxcel.download_binary(version=None, force=False) -> str, which returns the resolved path. mlxcel.find_cached_binary() and mlxcel.clear_cache() inspect and reset the cache.
The cache lives under the platform's user cache directory, keyed by version so releases coexist:
| Platform | Path |
|---|---|
| macOS | ~/Library/Caches/mlxcel/bin/<version>/bin/mlxcel |
| Linux | ~/.cache/mlxcel/bin/<version>/bin/mlxcel |
The version directory is installed as a unit, not just the executable, and keeps the archive's relative layout — the runtime files stay in the engine's directory — because the engine resolves them relative to its own location:
| Path | Contents |
|---|---|
<version>/bin/mlxcel |
the engine |
<version>/bin/mlx.metallib |
macOS only: Metal kernels, found in the engine's own directory |
<version>/bin/mlxcel-server |
macOS only: companion server binary. The Linux asset ships no server, and the client never fetches one |
<version>/include/... |
Linux only: CCCL / CUTLASS headers the runtime JIT compiles against |
On macOS a lone mlxcel still runs ordinary subcommands such as --version, but any
code path that loads a Metal kernel (inference, tune) traps with SIGTRAP and prints
nothing, because MLX's Metal device loader searches only the binary's own directory; the
Homebrew formula installs the same three files together. On Linux the JIT looks for
<exe-dir>/../include, which is where the header tree is placed.
Platforms and assets:
| OS / arch | Release asset |
|---|---|
| macOS arm64 | mlxcel-macos-aarch64.zip |
| Linux x86_64 | mlxcel-linux-x86_64-cuda13.zip |
| Linux aarch64 | mlxcel-linux-aarch64-cuda13.zip |
Anything else — Windows, macOS Intel — has no published binary; managed mode raises MlxcelServerError naming the connect-mode and manual-install routes.
Set MLXCEL_NO_DOWNLOAD=1, or pass auto_download=False, to forbid the automatic download. An explicitly installed binary is still found and used; only step 5 is skipped. This is the setting for a locked-down host that must not fetch from the network. An explicit python -m mlxcel install is a deliberate request and is not suppressed by this variable.
The client pins the engine release it provisions (currently 0.8.1) so a client release always fetches a binary it was tested with rather than silently tracking "latest". MLXCEL_RELEASE overrides it for a power user, and --version overrides both for one install. An installed binary of any version found on PATH, or passed with binary= / MLXCEL_BIN, is used regardless. The provisioning cache is different: it is keyed by version, so a cached engine for some other release is picked up only when you ask for that version (the pin, MLXCEL_RELEASE, or --version).
The Linux assets are built against CUDA 13. If your host runs a different CUDA, the downloaded binary may not run: use connect mode against a matching server, or install an engine built for your toolkit and pass it with binary= / MLXCEL_BIN.
A download is never executed unless its sha256 matched the published .sha256 sibling.
Two header layouts are refused outright rather than installed: a Linux archive
whose bin/ is not accompanied by its include/ header tree, and an archive that
puts an include entry anywhere between the engine's own directory and the archive
root other than the single tree the install lifts to <install>/include — a sibling
of the engine, or higher up beside a package directory that was named something other
than bin/. Either way the install is refused now rather than completed; a Linux
engine that did lose its header tree would only fail later, at the first kernel
compile, which is worse than a clean provisioning error. A mismatch or an empty/malformed checksum file raises MlxcelServerError and leaves nothing runnable behind. An HTTP failure (offline, a missing release) raises the same error with the manual-install hint rather than hanging.
Instead of provisioning, install the engine yourself and the client will find it:
brew install lablup/tap/mlxcel # macOS arm64
# or build from source and add target/release to PATHThen pass binary=/path/to/mlxcel, set MLXCEL_BIN, or put it on PATH. See Installation for building the binary.
Connect mode never needs a local engine: pass base_url= or socket= to reach a running server.
For a supported platform with an unsupported accelerator, or for any custom setup, this table matches the manual download: pick the asset for your OS/arch from the releases page, verify it with the sibling .sha256, and pass the extracted binary with binary=.
Pass a model and the client spawns mlxcel serve, waits until the server reports ready, and stops it on exit. The model loads and warms up before the listener binds, so a first run that downloads weights can take a while; the client polls /health with a generous startup_timeout (default 600 seconds) and watches the child process for an early exit.
import mlxcel
with mlxcel.LLM("mlx-community/Qwen3-4B-4bit") as llm:
text = llm.generate("def fib(n):", max_tokens=128, temperature=0.7)
print(text)
reply = llm.chat([{"role": "user", "content": "Hello"}], max_tokens=64)
print(reply)
print(llm.model) # resolved model id, auto-discovered from /v1/models
print(llm.models()) # ["<id>"]
ids = llm.tokenize("hello world")
print(llm.detokenize(ids))The context manager (with) is the recommended form; it guarantees shutdown. The client also registers an atexit cleanup and a best-effort finalizer so a leaked handle still stops the server.
Useful managed-mode arguments: binary=, auto_download=, host=/port= (forces TCP and binds there), socket= (an explicit Unix socket path), api_key=, ctx_size=, n_predict=, alias=, warmup=, extra_args=[...] (forwarded verbatim to mlxcel serve), and startup_timeout=.
The last group (ctx_size=, n_predict=, alias=, warmup=, extra_args=) travels through **server_kwargs: any extra keyword argument configures the spawned mlxcel serve process rather than the client.
with mlxcel.LLM(
"mlx-community/Qwen3-4B-4bit",
ctx_size=8192,
warmup=False,
extra_args=["--parallel", "1"],
) as llm:
print(llm.generate("hello", max_tokens=32))Pass base_url= or socket= (but not a model) to talk to a server you started yourself. No subprocess is launched or managed.
# TCP
llm = mlxcel.LLM(base_url="http://localhost:8080/v1")
# Unix domain socket
llm = mlxcel.LLM(socket="/tmp/mlxcel.sock")
print(llm.generate("Hello"))
llm.close()Start a matching server with the CLI:
# TCP
mlxcel serve -m mlx-community/Qwen3-4B-4bit --host 127.0.0.1 --port 8080
# Unix domain socket: a --host ending in .sock selects socket mode
mlxcel serve -m mlx-community/Qwen3-4B-4bit --host /tmp/mlxcel.sockPassing a model together with base_url= or transport= raises MlxcelError, because the mode would be ambiguous. socket= is the exception: alongside a model it is the bind path for the spawned server (see the recipe below), and without a model it is a connect target.
On a shared machine, the default socket path under /tmp is world-readable: any local user can connect to the server you spawned and send requests. If that matters for your deployment, pass an explicit socket= path under a directory only you can read, for example one under $XDG_RUNTIME_DIR (mode 0700, owned by your uid):
import os, pathlib, mlxcel
runtime_dir = pathlib.Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"))
runtime_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
with mlxcel.LLM("mlx-community/Qwen3-4B-4bit", socket=str(runtime_dir / "mlxcel.sock")) as llm:
print(llm.generate("hello"))The CLI equivalent is mlxcel serve --host "$XDG_RUNTIME_DIR/mlxcel.sock".
The default is the same short name under /tmp on macOS too: $TMPDIR there resolves to a long /var/folders/... path that would blow past the sun_path limit, so the client does not use it. The /tmp caveat above therefore applies to macOS as well, and on a shared macOS host the explicit socket= above is the way to keep the socket private. On Linux without an active login session, $XDG_RUNTIME_DIR may be absent; fall back to a 0700 subdirectory under your home directory if needed.
stream and chat_stream yield text deltas as they arrive.
with mlxcel.LLM("mlx-community/Qwen3-4B-4bit") as llm:
for delta in llm.stream("Write a haiku about autumn"):
print(delta, end="", flush=True)
for delta in llm.chat_stream([{"role": "user", "content": "List three uses for a Pi."}]):
print(delta, end="", flush=True)A runnable version of this example lives at python/examples/streaming.py.
chat returns the assistant message content as a string.
messages = [
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "What is MLX?"},
]
print(llm.chat(messages, max_tokens=128, temperature=0.3))Generation methods accept OpenAI sampling fields directly: max_tokens, temperature, top_p, stop, seed, presence_penalty, frequency_penalty, logit_bias, and response_format. Server-specific knobs that are not part of the OpenAI schema (top_k, min_p, top_n_sigma, typical_p, repetition_penalty, DRY settings, xtc_probability / xtc_threshold, and the vLLM-compatible loop-detection fields max_pattern_size / min_pattern_size / min_count, and ignore_eos) are forwarded in the request body. top_k at or above the model's vocabulary size keeps every token, the same as 0 (disabled), as in llama-server. xtc_probability (0.0-1.0, default 0.0, disabled) is the per-step chance that XTC (Exclude Top Choices) removes all but the single least-probable token among those whose probability exceeds xtc_threshold (0.0-0.5, default 0.1). The threshold is tested against the renormalised distribution that remains after top_k, top_p and min_p have run, not against the raw model distribution, matching the llama-server chain; both are validated on /v1/chat/completions, /v1/completions, and /v1/responses, and an out-of-range value returns a 400 before generation starts. top_n_sigma (default 0.0, disabled) keeps only the tokens whose raw logit lies within N standard deviations of the row maximum before the temperature / top-k / top-p / min-p chain runs, which keeps sampling stable at high temperature; it must be finite and >= 0.0 on the OpenAI-shaped endpoints (a negative value returns a 400). The native /completion spelling of the field lands together with its llama-server compatibility-manifest entry (#1436). typical_p (default 1.0, disabled) enables locally typical sampling: tokens whose surprisal is closest to the row entropy are kept, in typicality order, until typical_p probability mass accumulates; it must be finite and in (0.0, 1.0] on the OpenAI-shaped endpoints (400 otherwise), the native /completion field mirrors llama-server's limit-free schema by resolving a present out-of-range value to the explicit disabled form, and the server-wide --typical / --typical-p flag sets the default applied when a request omits the field. Since #1436 the repetition, frequency, and presence penalties follow llama-server's repeat_last_n window semantics: repetition_context_size (alias repeat_last_n) bounds them to the last N tokens, 0 disables them, and an absent field falls back to the server-wide --repeat-last-n default of 64 (previously the whole history was always scanned). DRY likewise adopts the b10621 sentinels: dry_penalty_last_n: 0 disables DRY, the CLI's -1 scans the full history, and a dry_base below 1.0 falls back to the server default. Server-wide defaults also exist for top_n_sigma (--top-nsigma, -1.0 or 0.0 disabled), XTC (--xtc-probability, --xtc-threshold), end-of-sequence suppression (--ignore-eos), and stop strings (-r / --reverse-prompt, repeatable). You can also pass an explicit extra_body={...} for arbitrary server fields; values you set there win on conflict.
llm.generate("Once upon a time", max_tokens=200, top_p=0.9, top_k=40, min_p=0.05)
llm.generate("...", extra_body={"repetition_penalty": 1.1})The server's llguidance-backed constrained decoding honors response_format, so you can require schema-valid JSON.
import json
schema = {
"type": "json_schema",
"json_schema": {
"name": "person",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"required": ["name", "age"],
"additionalProperties": False,
},
},
}
reply = llm.chat(
[{"role": "user", "content": "Invent a person as JSON."}],
response_format=schema,
max_tokens=128,
)
person = json.loads(reply)A runnable version of this example lives at python/examples/structured_output.py; it also issues the same request through the raw openai_client.
For anything the convenience methods do not cover (tools, logprobs, vision and audio inputs, the Responses API), reach for the configured OpenAI client directly. It is wired to the same transport, so TCP and Unix-socket setups both work.
oai = llm.openai_client # openai.OpenAI (or openai.AsyncOpenAI for AsyncLLM)
oai.chat.completions.create(
model=llm.model,
messages=[{"role": "user", "content": "Weather in SF?"}],
tools=[...],
)mlxcel.AsyncLLM mirrors the synchronous API with async/await and async iterators, backed by openai.AsyncOpenAI and httpx.AsyncClient.
import asyncio
import mlxcel
async def main():
async with mlxcel.AsyncLLM("mlx-community/Qwen3-4B-4bit") as llm:
print(await llm.generate("def fib(n):", max_tokens=128))
async for delta in llm.stream("Write a haiku"):
print(delta, end="", flush=True)
asyncio.run(main())The managed-server lifecycle (spawn and readiness polling) runs synchronously inside the constructor since it is a one-time blocking setup; every generation call is async. The model id resolves lazily on the first generation call, so read llm.model only after generate, stream, chat or chat_stream has run; reading it earlier raises MlxcelError. models() lists what the server advertises without resolving the id. The first constructor argument selects the mode: model= alone means managed mode (a server is spawned), and combining it with base_url= or transport= raises MlxcelError rather than overriding the id of the server you are already talking to.
| Exception | Raised when |
|---|---|
MlxcelError |
base class for all client errors (also used for ambiguous arguments) |
MlxcelServerError |
a managed server fails to launch, become ready, or stay alive (carries the captured stderr tail); also every provisioning failure — no installed binary could be found or provisioned, the platform has no published asset, the requested release does not exist, or the downloaded archive fails its checksum or layout check |
MlxcelTimeoutError |
the managed server does not become ready within startup_timeout |
HTTP and API errors from the server propagate as native openai SDK exceptions (for example openai.APIStatusError), so status codes and response bodies stay visible. This covers the OpenAI-shaped routes (/v1/*). The native tokenize and detokenize methods post to /tokenize and /detokenize through a plain httpx client, so a server-side failure there raises httpx.HTTPStatusError (and a transport failure httpx.RequestError), not an openai type. The Mlxcel* types cover two things: the managed-server lifecycle, and client-side setup and provisioning — locating or downloading the engine binary. They do not wrap a response that the running server actually produced.
- Server never becomes ready. The first run downloads weights before binding the listener. Increase
startup_timeout, and enable logging to watch progress:logging.getLogger("mlxcel.server").setLevel(logging.INFO). Server stderr (including download and load progress) is forwarded to that logger. - Engine provisioning progress. The client announces a multi-hundred-megabyte engine download at
WARNINGon themlxcel.provisionlogger, so the line appears with no logging configuration. Set that logger toDEBUGto also see cache hits and transient retries:logging.getLogger("mlxcel.provision").setLevel(logging.DEBUG). MlxcelServerErroron startup with a stderr tail. The child process exited before becoming ready. The attached stderr usually names the cause (model not found, out of memory, bad flag).- Binary not found. Install one (
brew install lablup/tap/mlxcel, or build it), passbinary="/path/to/mlxcel", setMLXCEL_BIN, or putmlxcelonPATH. Without any of those, managed mode downloads the pinned release — unlessMLXCEL_NO_DOWNLOAD=1orauto_download=Falseforbids it, in which case only the installed-binary lookup runs and its error names those routes. - Provisioning failed.
python -m mlxcelerrors name what went wrong:HTTP 404is usually raised while fetching the asset's.sha256sibling first, and means no asset is published for that OS/arch and release — almost always aMLXCEL_RELEASE/--versionthat does not exist. An unsupported platform never reaches this point: it raisesNo prebuilt mlxcel binary is published for …before any request.Checksum mismatchmeans the download was corrupt or tampered with, and nothing was run — retry, and if it repeats download the asset manually and pass it withbinary=. - Unix socket path too long.
sun_pathis about 104 bytes on macOS and 108 on Linux. On macOS,$TMPDIRresolves to a long/var/folders/...path, so the client defaults the socket to a short name under/tmpinstead. If your explicitsocket=path exceeds the limit, the client raises a clear error; pass a shorter path. - Port already in use (TCP). In managed mode without an explicit
port=, the client picks a free ephemeral port. Passport=only when you need a fixed one.