HTTP API
dlm serve starts a dependency-free HTTP server that speaks two dialects — the OpenAI API and the Anthropic Messages API. Point either SDK at dlm with a base-URL change and it talks to it unchanged.
Endpoints
| Method | Path | Purpose |
|---|---|---|
POST | /v1/chat/completions | OpenAI chat completion (with optional SSE streaming). |
POST | /v1/completions | OpenAI legacy text completion on a raw prompt (with optional SSE streaming). |
POST | /v1/embeddings | OpenAI embeddings for one or several inputs. |
POST | /v1/messages | Anthropic Messages API (with SSE streaming). |
POST | /v1/messages/count_tokens | Count tokens for an Anthropic-shaped request without generating. |
GET | /v1/models | List the served model. |
GET | /metrics | Prometheus counters and gauges. Requires the key under --api-key. |
GET | /v1/telemetry | SSE stream of per-layer flow events. Only with --telemetry; requires the key under --api-key. |
GET | /health | Liveness check (also GET / and /healthz). The only routes that stay open under --api-key. |
Chat completions
Post an OpenAI-shaped request. Add "stream": true to receive the reply token by token as Server-Sent Events.
curl http://127.0.0.1:8000/v1/chat/completions -H 'Content-Type: application/json' -d '{"model":"dlm","messages":[{"role":"user","content":"Hello"}],"max_tokens":32}'$ response
{"id":"chatcmpl-…","object":"chat.completion","model":"dlm",
"choices":[{"index":0,"message":{"role":"assistant",
"content":"Hello! How can I help?"},
"finish_reason":"stop","logprobs":null}],
"usage":{"prompt_tokens":9,"completion_tokens":7,
"total_tokens":16}}
Request fields
| Field | Notes |
|---|---|
model | Any string — dlm serves one model, and echoes this back. Omitted → the served model’s id (see List models). |
messages | Required. Array of { role, content } turns, rendered with the server’s chat template. content is a string or an array of parts — text parts are joined; image_url parts go to a model with a vision tower (Gemma 3 4B+, as base64 data: URLs; remote URLs are refused) and are dropped otherwise — and null reads as empty. Assistant tool_calls and tool turns are accepted — see Tool calling. |
max_tokens | Cap on generated tokens. Omitted → generation runs to EOS (or a stop sequence), clamped to what is left of the context window. |
stream | true → SSE chunks; false (default) → one JSON response. |
n | Number of choices, 1–16 (default 1). See Multiple choices below. |
logprobs | true → per-token log-probabilities; top_logprobs (0–20) adds the most likely alternatives. |
tools | Functions the model may call, with tool_choice auto (default) or none. ChatML, Llama 3.1/3.2 and Mistral v0.3 templates. |
response_format | json_object or json_schema; or grammar (GBNF). See Structured output. |
priority | Queue priority, lower admitted first (default 0). See Queueing. |
temperature | Plus top_p, top_k, min_p, repetition_penalty, seed, stop, logit_bias, frequency_penalty, presence_penalty and the dry_* fields — see Sampling parameters below. |
POST /v1/completions is the legacy OpenAI text-completion shape: send a raw prompt string instead of messages (no chat template is applied) and get back a text_completion object with the reply in choices[].text. It takes the same sampling fields, n, priority, response_format / grammar and "stream": true as chat completions; logprobs there is an integer (0–20), and tools are chat-only.Multiple choices & log-probabilities
n (1–16, both OpenAI endpoints) returns that many completions of the prompt, queued together so they decode in one batch and share the prompt’s cached prefix. A sampled choice i draws with seed seed + i, so the choices differ and each can be reproduced alone. Streamed chunks carry each choice’s index, every choice ends with its own finish_reason, and usage counts the prompt once.
Chat’s logprobs: true returns choices[].logprobs.content[] — each token’s token, logprob, bytes and top_logprobs (as many as top_logprobs asks for). /v1/completions takes logprobs: N and returns tokens, token_logprobs, top_logprobs and text_offset. Both stream, each chunk carrying the tokens whose text it delivers. Values come from the model’s distribution before temperature, penalties or a grammar reshape it, and asking for them does not change what is generated; such a request decodes without speculation.
Tool calling
On chat, models with the chatml (Qwen2.5, Qwen3), llama3 (Llama 3.1/3.2) and mistral (Mistral v0.3) templates can call functions. tools go into the prompt exactly as each model’s own template writes them, and the reply’s calls (Qwen’s <tool_call> blocks, Llama’s bare JSON object, Mistral’s [TOOL_CALLS]) come back as OpenAI tool_calls — arguments a JSON string, content null when there is no text — with finish_reason: "tool_calls".
curl http://127.0.0.1:8000/v1/chat/completions -H 'Content-Type: application/json' -d '{"model":"dlm","messages":[{"role":"user","content":"What is the weather in Paris?"}],"tools":[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]}'$ response
{"choices":[{"index":0,"message":{"role":"assistant",
"content":null,"tool_calls":[{"id":"call_…_0",
"type":"function","function":{"name":"get_weather",
"arguments":"{\"city\":\"Paris\"}"}}]},
"finish_reason":"tool_calls",…}],…}
- Send the result back as a
toolmessage after the assistant message with itstool_calls; both render back into the prompt for the next turn. - Streamed, text goes out until a call starts, and the calls follow whole in one delta at the end.
tool_choicetakesautoornone; forcing a specific call is refused with a 400, as istoolson any other template (Gemma’s has no tool format). Llama 3 takes one call per turn, as its template does.- Whether a model calls well is the model’s: Qwen2.5-1.5B and Qwen3-0.6B do, Qwen2.5-0.5B tends to answer instead. The Llama 3 and Mistral formats are checked against their templates’ output, not yet on the models themselves.
Structured output
On both OpenAI generation endpoints, the output can be held to a format — every time, not usually: a token the grammar cannot take is never emitted, and EOS only once the grammar is complete.
"response_format": {"type": "json_object"}— a JSON object.{"type": "json_schema", "json_schema": {"schema": …}}— JSON of that shape.nameandstrictare accepted and ignored; the schema is always enforced."grammar"— a GBNF grammar in llama.cpp’s format. Set it or a JSONresponse_format, not both.
curl http://127.0.0.1:8000/v1/chat/completions -H 'Content-Type: application/json' -d '{"model":"dlm","messages":[{"role":"user","content":"Name a city and its country."}],"response_format":{"type":"json_schema","json_schema":{"schema":{"type":"object","properties":{"city":{"type":"string"},"country":{"type":"string"}},"required":["city","country"]}}}}'type (object, array, string, number, integer, boolean, null, or a list of them), properties with required (no other keys), items, enum, const, anyOf and oneOf. $ref, allOf, not, if and patternProperties are refused with a 400 rather than silently ignored, as is a grammar that does not parse. A constrained request decodes without speculation.Embeddings
POST /v1/embeddings returns, for each input, its final-normed hidden states pooled to one vector at unit length. serve --embedding-pooling auto (the default) follows a sentence-transformers export’s 1_Pooling/config.json (mean or last token), and otherwise takes the last token, the pooling decoder embedding models such as Qwen3-Embedding and gte-Qwen2 are trained for; last or mean force one. A chat model’s embeddings work but are not tuned for retrieval.
curl http://127.0.0.1:8000/v1/embeddings -H 'Content-Type: application/json' -d '{"model":"dlm","input":["first text","second text"]}'$ response
{"object":"list","data":[
{"object":"embedding","index":0,"embedding":[0.0123,…]},
{"object":"embedding","index":1,"embedding":[-0.0041,…]}],
"model":"dlm","usage":{"prompt_tokens":4,"total_tokens":4}}
| Field | Notes |
|---|---|
input | Required. A string, an array of strings, an array of token ids, or an array of id arrays. Each input is 1 to context-length tokens; text is tokenized as-is (no chat template). |
encoding_format | float (default) or base64 — the little-endian f32 bytes, which the OpenAI Python SDK asks for by default. |
dimensions | Keep the leading N dimensions, scaled back to unit length. |
Anthropic Messages API
POST /v1/messages accepts an Anthropic-shaped request, so the Anthropic SDKs work against dlm. A top-level system field is folded in as a leading system message, and content may be a string or a list of text blocks.
curl http://127.0.0.1:8000/v1/messages -H 'Content-Type: application/json' -H 'x-api-key: dlm' -d '{"model":"dlm","max_tokens":128,"messages":[{"role":"user","content":"Hello"}]}'$ response
{"id":"msg-…","type":"message","role":"assistant",
"model":"dlm",
"content":[{"type":"text","text":"Hello! How can I help?"}],
"stop_reason":"end_turn","stop_sequence":null,
"usage":{"input_tokens":9,"output_tokens":7}}
| Field | Notes |
|---|---|
messages | Required. Each content is a string or a list of text blocks. |
max_tokens | Anthropic requires it; if absent dlm runs to EOS, clamped to what is left of the context window. |
system | Optional string or blocks — becomes a leading system message. |
temperature | Plus top_p, top_k, min_p, repetition_penalty, stop_sequences. The OpenAI-only fields — seed, logit_bias, the penalties, DRY, n, logprobs, tools, structured output and priority — are not read here. |
POST /v1/messages/count_tokens takes the same messages and system and returns {"input_tokens": N} without generating.
Streaming
Set "stream": true to stream the reply as Server-Sent Events, following the sequence Anthropic clients expect:
message_start— the opening message envelope.content_block_start— an empty text block at index 0, followed by aping.content_block_delta— a run oftext_deltaevents as the text completes.content_block_stop— the text block closes.message_delta— the finalstop_reason,stop_sequenceandoutput_tokens.message_stop— the stream ends.
event: and a data: line. stop_reason is end_turn when the model emits EOS, stop_sequence (with the matched stop_sequence) when a stop is hit, and max_tokens at the cap.Sampling parameters
A temperature above 0 selects the sampler; absent or 0 decodes greedily, and top_p, top_k, min_p and repetition_penalty then have no effect. Those five are honored on the chat, completions and messages endpoints. The logit adjustments below them are OpenAI-endpoint only and apply under any sampler, greedy included. An out-of-range value is a 400, not clamped.
| Parameter | Effect |
|---|---|
temperature | Softmax temperature. 0 or absent → deterministic greedy. |
top_p | Nucleus sampling threshold (default 1, off). |
top_k | Top-k sampling cutoff (default 0, off). |
min_p | Min-p truncation — drop tokens below a fraction of the top probability (default 0, off). |
repetition_penalty | Penalize already-generated tokens to curb loops (default 1, off). |
seed | Seed the sampler for reproducibility (OpenAI endpoints; defaults to the request id). |
stop / stop_sequences | Stop sequences that truncate the completion (OpenAI: a string or a list; Anthropic: a list). |
max_tokens | Cap the number of generated tokens. Absent → run to EOS, clamped to the context window. |
logit_bias | Token id (as a string) → bias in [-100, 100] added to its logit; -100 bans a token. A key outside the vocabulary is a 400. |
frequency_penalty | -2 to 2 (default 0). Subtracted from a token’s logit once per time it has been generated (prompt tokens don’t count). |
presence_penalty | -2 to 2 (default 0). Subtracted once from any token already generated. |
dry_multiplier | DRY (llama.cpp’s fields): penalizes the token that would extend a run already seen in the context. 0 (default) leaves it off. |
dry_base | DRY growth base, at least 1 (default 1.75). Penalty = multiplier · base^(run − allowed_length). |
dry_allowed_length | Run length that goes unpenalized, at least 1 (default 2). |
dry_sequence_breakers | Strings a run does not cross (default ["\n", ":", "\"", "*"]). |
List models
GET /v1/models returns the single served model in the OpenAI list shape. Its id is the checkpoint’s own name — the model directory, or a GGUF file’s name without the extension. Requests may still name any model; the name they send is echoed back.
curl http://127.0.0.1:8000/v1/models$ response
{"object":"list","data":[{"id":"qwen2.5-0.5b",
"object":"model","created":…,"owned_by":"dlm"}]}
Queueing & priority
A request starts once a batch slot (--max-batch) is free — and, where the GPU pages KV, once the pool can hold its prompt plus max_tokens; until then it waits in the queue. A request’s priority (OpenAI endpoints, vLLM’s field, default 0) orders that queue — lowest first, arrival order within one. It decides who is admitted next; it does not preempt a running request.
By default a request waits as long as it takes. Start the server with --queue-timeout SECS to turn away one that has waited longer, with 503 and Retry-After: 1. Every endpoint waits for admission before answering, so even a "stream": true request gets a real HTTP error rather than a stream that breaks. A request already decoding is never cut off.
dlm serve --model-path /path/to/model --queue-timeout 30Metrics
GET /metrics exposes Prometheus-format counters and gauges — scrape it with any Prometheus-compatible collector. Every request is also written to an access log on stderr (METHOD PATH → status (Nms)).
| Series | Meaning |
|---|---|
dlm_requests_total | Requests served. |
dlm_prompt_tokens_total | Prompt tokens processed. |
dlm_completion_tokens_total | Completion tokens generated. |
dlm_requests_running | Gauge — requests decoding now. |
dlm_requests_waiting | Gauge — requests queued for a batch slot. |
dlm_kv_free_tokens | Gauge — KV cache tokens free in the pool. Present only where the GPU pages KV. |
Under --stream, the layer-streaming cache also reports its hit rate and prefetch behavior — watch the miss and prefetch-depth series when tuning performance:
| Series | Meaning |
|---|---|
dlm_stream_layer_hits_total | Layer fetches served from the resident window. |
dlm_stream_layer_misses_total | Fetches that blocked on a load. |
dlm_stream_layer_evictions_total | Layers evicted from the window. |
dlm_stream_layer_prefetched_total | Layers loaded ahead by the prefetch worker. |
dlm_stream_prefetch_depth | Gauge — layers prefetched ahead (auto-tuned under --auto-prefetch). |
dlm_stream_expert_hits_total | MoE on the GPU — routed-expert fetches served from the VRAM expert cache (with _misses_total and _evictions_total). |
Errors
Failures return a JSON error body with the appropriate status code. See the Errors & status codes reference for the full list.
Authentication
Start the server with --api-key to require a key on every route except the liveness probes (/, /health, /healthz) — GET /metrics included, since it leaks request and token counts. Both header styles are accepted — Authorization: Bearer <key> (OpenAI) or x-api-key: <key> (Anthropic) — so either SDK authenticates unchanged. The request body is size-capped to guard against a hostile Content-Length.
dlm serve --model-path /path/to/model --api-key sk-secretcurl -H 'Authorization: Bearer sk-secret' http://127.0.0.1:8000/v1/modelscurl -H 'x-api-key: sk-secret' http://127.0.0.1:8000/v1/modelsBrowser clients (CORS)
A page served from another origin cannot read dlm’s replies unless the server allows it — the request succeeds and the browser discards the answer. --cors-origin answers the browser’s OPTIONS preflight (no key needed) and tags every reply with Access-Control-Allow-Origin. Pass one origin, or * for any — on a shared network, only behind --api-key. Off by default.
dlm serve --model-path /path/to/model --cors-origin http://localhost:3000Tokenizers & chat templates
- Real tokenizers load from HF
tokenizer.json(BPE, with special tokens),vocab.json+merges.txt, or a GGUF file’s own metadata. --chat-templatedefaults toauto, which recognizes the checkpoint’s Jinjachat_templateby its control markers — ChatML, Llama-3, Llama-2, Mistral, Gemma, Gemma 4, Phi-3 or DeepSeek-V2 — and adds the format’s end-of-turn token to the stop set. dlm does not run Jinja: an unrecognized template falls back toplainwith a warning. Name one to override:plain,chatml,llama3,llama2,mistral,gemma,phi3,deepseek.
Usage & speculative stats
When the server decodes speculatively (--draft-model-path or --speculative ngram), per-request acceptance is surfaced in the OpenAI usage response under a speculative block: draft_proposed, draft_accepted, acceptance_rate. Streaming responses carry it in a final usage-only chunk. It is reported for single-choice requests (n = 1).