Skip to main content

Crate infr_server

Crate infr_server 

Source
Expand description

OpenAI-compatible HTTP server (axum + SSE). Talks only to infr-engine — never the GPU.

Reference for the wire mapping (streaming, reasoning_content, tool_calls): the working shim at ~/Projects/scratch/dgemma-openai-server.py. See docs/plan.md “server”.

Routes (auth = gated by serve.api_key when one is configured — see auth_gate): GET /health -> 200 OK (open) GET /v1/models -> { object: “list”, data: [{ id, object, owned_by }] } (auth) GET /metrics -> Prometheus text exposition (see metrics) (auth) GET /status -> JSON: per-model backend, device, ctx, slots, memory (auth) POST /v1/chat/completions -> chat.completion | SSE chat.completion.chunk stream (auth) POST /v1/completions -> text_completion | SSE text_completion stream (raw prompt, no template) (auth)

Two process-level limits bound one request’s hold on a --parallel slot: serve.max_tokens_cap (tokens — see clamp_max_tokens) and serve.request_timeout_secs (wall clock — see request_timeout). Both are serve.* config, never read from the environment here.

Every route but /health also passes the Host check (host::host_gate, serve.allowed_hosts), which guards a keyless loopback server against DNS rebinding.

Delta mapping: Delta::Reasoning -> delta.reasoning_content Delta::Content -> delta.content Delta::ToolCall -> delta.tool_calls[] (finish_reason “tool_calls”)

Structs§

AppState
Shared server state — a non-empty, ordered set of hosted ModelEntrys. A request is routed to the entry whose id matches its model field; an unknown/empty model falls to the DEFAULT (the first entry). The single-model server is just the one-entry case, so its behaviour — and the hot path — is byte-identical to before this became multi-model.
AssistantMessage
ChatCompletionChunk
ChatCompletionResponse
ChatLogprobs
OpenAI’s choice.logprobs / choice.delta.logprobs.
ChatMessageDto
A single chat message. content may be a JSON string or a content-part array.
ChatOutcome
What one ChatGenerator::chat call produced: why it ended, plus the real token counts the handler needs for a truthful usage block (total = prompt + completion). Counts are what the generator actually tokenized/emitted — never a content.len()/4 estimate.
ChatRequest
Top-level chat completion request (OpenAI wire format).
ChatTokenLogprob
One token’s entry in ChatLogprobs::content. id is a llama.cpp-style extension; OpenAI clients ignore unknown fields.
ChatTokenLogprobAlt
ChunkChoice
CompletionChoice
ContextLengthExceeded
The request’s prompt does not fit the model’s context. A ChatGenerator returns it (as the anyhow error) so the server can answer 400 with OpenAI’s context_length_exceeded code: OpenAI clients retry a 5xx unchanged, but treat this code as final and shorten the conversation instead.
DeltaPayload
The delta field inside a streaming chunk. Fields absent when None.
DeviceMemory
A device memory snapshot.
GenParams
The validated, per-request generation config handed to ChatGenerator::chat. None fields mean “the request didn’t say” — the generator leaves the process default (INFR_TEMP / INFR_TOP_K / INFR_TOP_P / INFR_MAX_NEW) in charge for exactly those.
GeneratorStatus
Where a generator runs and how much room it has there, as crate::ChatGenerator::status reports it.
LogprobStops
A StopMatcher that carries each token’s log probability along with the text it produced, so the entries a reply reports are exactly those of the tokens whose text it returns. Shared by the chat route and /v1/completions.
ModelCard
ModelsResponse
OAIFunction
OAIToolCall
OpenAI-shaped tool call (used in both streaming and non-streaming responses).
ParamError
An OpenAI-shaped 400: {"error":{"message":..,"type":"invalid_request_error","param":..}}.
PreparedRequest
A request a ChatGenerator has readied in prepare: what the server reads before queueing it, plus the generator’s own state for chat_prepared, which the server carries without looking at.
PromptTokensDetails
StopMatcher
Incremental stop-sequence matcher over the DECODED text stream.
StreamOptions
OpenAI stream_options. With include_usage, a streamed reply ends with one extra chunk that carries usage and an empty choices array, just before [DONE].
TokenText
Text that is now safe to send, with the entries of the tokens it belongs to.
UsageInfo

Enums§

Finish
Why generation ended — the OpenAI finish_reason. The generator reports it; the handlers serialize it (a tool call still overrides to Finish::ToolCalls at the wire layer).
LogitBiasArg
A request’s logit_bias as the client sent it: the object’s entries in order with a repeated key kept (a JSON object map would silently merge it), or the JSON type sent instead of an object. null deserializes as an absent field.
ResponseFormat
What the reply must look like — a validated OpenAI response_format. {"type":"text"}, like an absent field, asks for nothing and never becomes a value.

Traits§

ChatGenerator
Generation backend the server drives — it never knows the model/GPU underneath. Implemented by the CLI’s per-arch adapters (infr-cli’s ParallelGenerator over infr_llama::ParallelSeam for the Vulkan seam; SeamGenerator wraps any infr_llama::ChatModel for the rest, including DiffusionGemmaChat — see docs/diffusion-gemma.md).

Functions§

build_router
Build the axum Router. Extracted so tests can call it with a AppState::headless state.
flatten_content
Flatten a DTO content field (string OR content-part array) to a plain String.
serve
Start the OpenAI-compatible server bound to addr, serving engine under model_id with n_parallel concurrent generation slots (--parallel N).
serve_multi
Start the server hosting SEVERAL models at once, each routed by its model_id and admitted with its own n_parallel slot count (entries[0] is the default route). This is the multi-device host (infr multi): each generator can be pinned to a different physical GPU, and the server dispatches a request to the generator for the model it names. Graceful shutdown drains EVERY model’s in-flight requests before any backend drops (the axum layer stops accepting, then each generation returns at its next abort poll — see shutdown_latched); when serve_multi returns, the runtime drops and every backend’s device is destroyed in turn.