Skip to content

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

MethodPathPurpose
POST/v1/chat/completionsOpenAI chat completion (with optional SSE streaming).
POST/v1/completionsOpenAI legacy text completion on a raw prompt (with optional SSE streaming).
POST/v1/embeddingsOpenAI embeddings for one or several inputs.
POST/v1/messagesAnthropic Messages API (with SSE streaming).
POST/v1/messages/count_tokensCount tokens for an Anthropic-shaped request without generating.
GET/v1/modelsList the served model.
GET/metricsPrometheus counters and gauges. Requires the key under --api-key.
GET/v1/telemetrySSE stream of per-layer flow events. Only with --telemetry; requires the key under --api-key.
GET/healthLiveness 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

FieldNotes
modelAny string — dlm serves one model, and echoes this back. Omitted → the served model’s id (see List models).
messagesRequired. 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_tokensCap on generated tokens. Omitted → generation runs to EOS (or a stop sequence), clamped to what is left of the context window.
streamtrue → SSE chunks; false (default) → one JSON response.
nNumber of choices, 1–16 (default 1). See Multiple choices below.
logprobstrue → per-token log-probabilities; top_logprobs (0–20) adds the most likely alternatives.
toolsFunctions the model may call, with tool_choice auto (default) or none. ChatML, Llama 3.1/3.2 and Mistral v0.3 templates.
response_formatjson_object or json_schema; or grammar (GBNF). See Structured output.
priorityQueue priority, lower admitted first (default 0). See Queueing.
temperaturePlus 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",…}],…}

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.

$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"]}}}}'
Supported schema keywords: 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}}
FieldNotes
inputRequired. 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_formatfloat (default) or base64 — the little-endian f32 bytes, which the OpenAI Python SDK asks for by default.
dimensionsKeep 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}}
FieldNotes
messagesRequired. Each content is a string or a list of text blocks.
max_tokensAnthropic requires it; if absent dlm runs to EOS, clamped to what is left of the context window.
systemOptional string or blocks — becomes a leading system message.
temperaturePlus 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:

Each frame carries both an 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.

ParameterEffect
temperatureSoftmax temperature. 0 or absent → deterministic greedy.
top_pNucleus sampling threshold (default 1, off).
top_kTop-k sampling cutoff (default 0, off).
min_pMin-p truncation — drop tokens below a fraction of the top probability (default 0, off).
repetition_penaltyPenalize already-generated tokens to curb loops (default 1, off).
seedSeed the sampler for reproducibility (OpenAI endpoints; defaults to the request id).
stop / stop_sequencesStop sequences that truncate the completion (OpenAI: a string or a list; Anthropic: a list).
max_tokensCap the number of generated tokens. Absent → run to EOS, clamped to the context window.
logit_biasToken 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_multiplierDRY (llama.cpp’s fields): penalizes the token that would extend a run already seen in the context. 0 (default) leaves it off.
dry_baseDRY growth base, at least 1 (default 1.75). Penalty = multiplier · base^(run − allowed_length).
dry_allowed_lengthRun length that goes unpenalized, at least 1 (default 2).
dry_sequence_breakersStrings 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 30

Metrics

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)).

SeriesMeaning
dlm_requests_totalRequests served.
dlm_prompt_tokens_totalPrompt tokens processed.
dlm_completion_tokens_totalCompletion tokens generated.
dlm_requests_runningGauge — requests decoding now.
dlm_requests_waitingGauge — requests queued for a batch slot.
dlm_kv_free_tokensGauge — 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:

SeriesMeaning
dlm_stream_layer_hits_totalLayer fetches served from the resident window.
dlm_stream_layer_misses_totalFetches that blocked on a load.
dlm_stream_layer_evictions_totalLayers evicted from the window.
dlm_stream_layer_prefetched_totalLayers loaded ahead by the prefetch worker.
dlm_stream_prefetch_depthGauge — layers prefetched ahead (auto-tuned under --auto-prefetch).
dlm_stream_expert_hits_totalMoE 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-secret
$curl -H 'Authorization: Bearer sk-secret' http://127.0.0.1:8000/v1/models
$curl -H 'x-api-key: sk-secret' http://127.0.0.1:8000/v1/models

Browser 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:3000

Tokenizers & chat templates

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).

Concurrent requests are continuously batched by a background scheduler, and each request’s output is identical to running it alone — independent of interleaving. See Architecture & math.