Skip to main content

Text generation

LocalAI generates text with the llama-cpp backend and with other backends, such as vllm and transformers. See also the Model compatibility for an up-to-date list of the supported model families.

Note:

  • You can also specify the model name as part of the OpenAI token.
  • If only one model is available, the API will use it for all the requests.

API Reference

Chat completions

https://platform.openai.com/docs/api-reference/chat

For example, to generate a chat completion, you can send a POST request to the /v1/chat/completions endpoint with the instruction as the request body:

curl http://localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{
  "model": "ggml-koala-7b-model-q4_0-r2.bin",
  "messages": [{"role": "user", "content": "Say this is a test!"}],
  "temperature": 0.7
}'

Available additional parameters: top_p, top_k, max_tokens, service_tier (see Request priority)

When a request omits max_tokens, the vLLM and SGLang backends do not cap generation at 200 tokens. Generation is bounded only by the context window of the model.

Reasoning models return their thinking in the reasoning field. When a model reasons and calls a tool in the same turn, see Interleaved Thinking with Tool Calls.

When stream: true is set and the llama.cpp backend fails before the first chunk, for example because the prompt exceeds the context size, the request fails with an HTTP error. The error message is not streamed as assistant content. An error after streaming has started is reported inside the stream.

Edit completions

https://platform.openai.com/docs/api-reference/edits

To generate an edit completion you can send a POST request to the /v1/edits endpoint with the instruction as the request body:

curl http://localhost:8080/v1/edits -H "Content-Type: application/json" -d '{
  "model": "ggml-koala-7b-model-q4_0-r2.bin",
  "instruction": "rephrase",
  "input": "Black cat jumped out of the window",
  "temperature": 0.7
}'

Available additional parameters: top_p, top_k, max_tokens.

Completions

https://platform.openai.com/docs/api-reference/completions

To generate a completion, you can send a POST request to the /v1/completions endpoint with the instruction as per the request body:

curl http://localhost:8080/v1/completions -H "Content-Type: application/json" -d '{
  "model": "ggml-koala-7b-model-q4_0-r2.bin",
  "prompt": "A long time ago in a galaxy far, far away",
  "temperature": 0.7
}'

Available additional parameters: top_p, top_k, max_tokens, service_tier (see Request priority)

Request priority

/v1/chat/completions, /v1/completions and /v1/responses accept the OpenAI service_tier field. It sets the priority class of the request. When requests wait for a free slot, a backend that queues requests (llama.cpp) serves a higher class first. Requests of one class are served in the order they arrive.

service_tierClassUse it for
flexbatch (-1)Work that nobody waits on, such as bulk jobs
auto, default or not setdefault (0)Normal requests
priorityinteractive (1)Requests that a person waits on

Any caller can lower the priority of its own requests with flex. Only an administrator can use priority. For other callers, LocalAI changes priority to default. On a server without authentication (no user accounts and no API keys), every caller can use priority. An unknown value returns HTTP 400.

The response includes the tier that LocalAI used in service_tier, in every chunk of a streamed chat or text completion too.

LocalAI also sets the class of its own requests. A chat in the web UI and a chat from a connector are interactive. Sub-agents, jobs, triggers, pages and the indexing of collections are batch.

curl http://localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{
  "model": "my-model",
  "service_tier": "flex",
  "messages": [{"role": "user", "content": "Summarize this report."}]
}'

List models

You can list all the models available with:

curl http://localhost:8080/v1/models

Anthropic Messages API

LocalAI supports the Anthropic Messages API, which is compatible with Claude clients. This endpoint provides a structured way to send messages and receive responses, with support for tools, streaming, and multimodal content.

Endpoint: POST /v1/messages or POST /messages

Reference: https://docs.anthropic.com/claude/reference/messages_post

Basic Usage

curl http://localhost:8080/v1/messages \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "ggml-koala-7b-model-q4_0-r2.bin",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "Say this is a test!"}
    ]
  }'

Request Parameters

ParameterTypeRequiredDescription
modelstringYesThe model identifier
messagesarrayYesArray of message objects with role and content
max_tokensintegerYesMaximum number of tokens to generate (must be > 0)
systemstringNoSystem message to set the assistant’s behavior
temperaturefloatNoSampling temperature (0.0 to 1.0)
top_pfloatNoNucleus sampling parameter
top_kintegerNoTop-k sampling parameter
stop_sequencesarrayNoArray of strings that will stop generation
streambooleanNoEnable streaming responses
toolsarrayNoArray of tool definitions for function calling
tool_choiceobjectNoTool choice strategy: {"type": "auto"}, {"type": "any"}, {"type": "none"}, or {"type": "tool", "name": "..."}. The bare strings “auto”, “any” and “none” are accepted too
metadataobjectNoPer-request metadata passed to the backend (e.g., {"enable_thinking": "true"})

Message Format

Messages can contain text or structured content blocks:

curl http://localhost:8080/v1/messages \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ggml-koala-7b-model-q4_0-r2.bin",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "What is in this image?"
          },
          {
            "type": "image",
            "source": {
              "type": "base64",
              "media_type": "image/jpeg",
              "data": "base64_encoded_image_data"
            }
          }
        ]
      }
    ]
  }'

Tool Calling

The Anthropic API supports function calling through tools:

curl http://localhost:8080/v1/messages \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ggml-koala-7b-model-q4_0-r2.bin",
    "max_tokens": 1024,
    "tools": [
      {
        "name": "get_weather",
        "description": "Get the current weather",
        "input_schema": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state"
            }
          },
          "required": ["location"]
        }
      }
    ],
    "tool_choice": {"type": "auto"},
    "messages": [
      {"role": "user", "content": "What is the weather in San Francisco?"}
    ]
  }'

Streaming

Enable streaming responses by setting stream: true:

curl http://localhost:8080/v1/messages \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ggml-koala-7b-model-q4_0-r2.bin",
    "max_tokens": 1024,
    "stream": true,
    "messages": [
      {"role": "user", "content": "Tell me a story"}
    ]
  }'

Streaming responses use Server-Sent Events (SSE) format with event types: message_start, content_block_start, content_block_delta, content_block_stop, message_delta, and message_stop.

Response Format

{
  "id": "msg_abc123",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "This is a test!"
    }
  ],
  "model": "ggml-koala-7b-model-q4_0-r2.bin",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 10,
    "output_tokens": 5
  }
}

stop_reason is end_turn, tool_use, or max_tokens when the reply used up max_tokens.

Open Responses API

LocalAI supports the Open Responses API specification, which provides a standardized interface for AI model interactions with support for background processing, streaming, tool calling, and advanced features like reasoning.

Endpoint: POST /v1/responses or POST /responses

Reference: https://www.openresponses.org/specification

Basic Usage

curl http://localhost:8080/v1/responses \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ggml-koala-7b-model-q4_0-r2.bin",
    "input": "Say this is a test!",
    "max_output_tokens": 1024
  }'

Reuse assistant messages

When you manage conversation history in your client, append assistant messages from a response’s output array to the next request’s input. Keep their content type as output_text. Use input_text for new user messages. Include earlier conversation items that the model still needs.

For example, submit this body to POST /v1/responses:

{
  "model": "ggml-koala-7b-model-q4_0-r2.bin",
  "input": [
    {
      "type": "message",
      "role": "user",
      "content": [{"type": "input_text", "text": "What is the capital of France?"}]
    },
    {
      "type": "message",
      "role": "assistant",
      "content": [{"type": "output_text", "text": "Paris is the capital of France."}]
    },
    {
      "type": "message",
      "role": "user",
      "content": [{"type": "input_text", "text": "Which river flows through it?"}]
    }
  ]
}

WebSocket Responses

Connect to ws://localhost:8080/v1/responses (or wss:// when TLS is enabled) and send response.create messages over the WebSocket. Only one response may be in progress on a connection. Wait for response.completed or response.failed for the active response before sending the next response.create. An error that rejects an invalid or additional response.create applies only to that rejected message; it does not terminate a response that is already in progress.

Set the WebSocket-only generate field to false to prepare a request without running inference:

{
  "type": "response.create",
  "model": "ggml-koala-7b-model-q4_0-r2.bin",
  "generate": false,
  "store": false,
  "input": "Say this is a test!"
}

LocalAI emits response.created followed by response.completed with no generated output. The completed response still has an ID that can continue the prepared request:

{
  "type": "response.create",
  "model": "ggml-koala-7b-model-q4_0-r2.bin",
  "store": false,
  "previous_response_id": "resp_abc123",
  "input": []
}

Response IDs created with store: false are available only on the WebSocket connection that created them and are removed when that connection closes. A previous_response_id chain can contain multiple responses; LocalAI replays the complete conversation from the oldest response through the referenced response before appending the new input. The replay includes server-side MCP tool calls and their results, which are stored as function_call and function_call_output output items. Keep store: false for every descendant of a connection-local response. LocalAI rejects a store: true response that depends on connection-local history because the resulting stored chain would be broken after the WebSocket closes.

After delivery, LocalAI discards buffered stream events for store: false responses but retains their request and final response for continuation. A connection admits at most 128 local responses and accepts a new local request only while its current serialized history plus that request is at most 64 MiB. When either admission threshold is reached, LocalAI returns connection_store_limit_reached; reconnect to start a new local history. With authentication enabled, globally stored response IDs can be continued only by the identity that created them.

Request Parameters

ParameterTypeRequiredDescription
modelstringYesThe model identifier
inputstring/arrayYesInput text or array of input items
max_output_tokensintegerNoMaximum number of tokens to generate
temperaturefloatNoSampling temperature
top_pfloatNoNucleus sampling parameter
instructionsstringNoSystem instructions
toolsarrayNoArray of tool definitions: function tools, and namespace entries such as the ones Codex sends for MCP servers. The model sees a namespace member as ns_{namespace}___{name}; the function_call items returned carry the namespace and name again
tool_choicestring/objectNoTool choice: “auto”, “required”, “none”, or specific tool. To force a namespace member, name it with namespace and name
streambooleanNoEnable streaming responses
backgroundbooleanNoRun request in background (returns immediately)
storebooleanNoWhether to store the response
reasoningobjectNoReasoning configuration with effort and summary
parallel_tool_callsbooleanNoAllow parallel tool calls
max_tool_callsintegerNoMaximum number of tool calls
presence_penaltyfloatNoPresence penalty (-2.0 to 2.0)
frequency_penaltyfloatNoFrequency penalty (-2.0 to 2.0)
top_logprobsintegerNoNumber of top logprobs to return
truncationstringNoTruncation mode: “auto” or “disabled”
text_formatobjectNoText format configuration
metadataobjectNoCustom metadata
service_tierstringNoPriority class: flex, default or priority. See Request priority

Input Format

Input can be a simple string or an array of structured items:

curl http://localhost:8080/v1/responses \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ggml-koala-7b-model-q4_0-r2.bin",
    "input": [
      {
        "type": "message",
        "role": "user",
        "content": "What is the weather?"
      }
    ],
    "max_output_tokens": 1024
  }'

A string input is a user chat message, not a raw text-completion prefix.

For models configured with template.use_tokenizer_template: true, LocalAI sends the input messages, instructions, history and tools to the backend as structured messages, and the backend applies the model’s native chat template. This applies to buffered and streaming responses. The same routing applies to /v1/chat/completions, /v1/messages and the Ollama /api/chat endpoint. Some backends (vLLM, SGLang, transformers and MLX) apply the chat template only when the prompt is empty. If LocalAI sent them a flattened prompt, they would continue the input text instead of answering it.

Streaming responses

Set "stream": true to receive Server-Sent Events. Each response.output_item.added event assigns an output_index to an item. Use that index and the item ID to associate later deltas and completion events with the same item.

If a request without explicit tools produces reasoning, the stream uses separate items for reasoning and answer text. Each item keeps its original index throughout the stream. The response.completed event includes both items in the same index order, followed by any automatically parsed tool calls.

Background Processing

Run requests in the background for long-running tasks:

curl http://localhost:8080/v1/responses \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ggml-koala-7b-model-q4_0-r2.bin",
    "input": "Generate a long story",
    "max_output_tokens": 4096,
    "background": true
  }'

The response will include a response ID that can be used to poll for completion:

{
  "id": "resp_abc123",
  "object": "response",
  "status": "in_progress",
  "created_at": 1234567890
}

Retrieving Background Responses

Use the GET endpoint to retrieve background responses:

# Get response by ID
curl http://localhost:8080/v1/responses/resp_abc123

# Resume streaming with query parameters
curl "http://localhost:8080/v1/responses/resp_abc123?stream=true&starting_after=10"

Canceling Background Responses

Cancel a background response that’s still in progress:

curl -X POST http://localhost:8080/v1/responses/resp_abc123/cancel

Multiple Replicas (Distributed Mode)

In distributed mode LocalAI replicates response metadata across frontend replicas, so retrieval, previous_response_id chaining and cancellation work regardless of which replica the load balancer picks:

  • GET /v1/responses/{id} returns the response from any replica.
  • POST /v1/responses/{id}/cancel is delegated over NATS to the replica that is actually generating, so generation really stops. If that replica is gone, the response is reported as cancelled without blocking.
  • Streaming resume (?stream=true&starting_after=N) works on any replica, because the event buffer is read from the database (see Durable Storage below). Without a database (it always exists in distributed mode, so this only concerns a build that cannot reach it) the buffer is in the memory of the replica that generates, and a resume that reaches another replica returns HTTP 409 naming the owning replica.

State mode (see the distributed-state rules): the response metadata is shared state, a SyncedMap with a database Store. The table is the source of truth, a replica that starts later loads the newest rows (up to 10000), and changes reach the other replicas as deltas over NATS. The events are not sent over NATS: every replica reads them from the table. The generation itself, and its cancel function, live on one replica, the owner of the response; a cancel reaches it over NATS and through the cancel_requested flag.

Durable Storage

When LocalAI has a database (authentication enabled, or distributed mode), stored responses and the events of a background run are kept in two tables, open_responses and open_response_events. Without a database the store stays in memory, as before, and ends with the process.

With the tables:

  • A response and its event buffer outlive a restart. GET /v1/responses/{id}, previous_response_id chaining and ?stream=true&starting_after=N read the tables, so any replica serves them and they work after a restart.
  • The owner writes events in batches: at once for any event that is not a .delta event, and for deltas every 250 ms or 64 events. If the process dies, the deltas of the last 250 ms are lost.
  • The buffer keeps the same caps as the memory store (8192 events and 64 MiB per response, oldest first). A resume below the oldest kept event returns HTTP 409 (ErrOffsetLost).
  • Every read still checks the owner of the response: a caller who did not create it gets 404. An item_reference finds only an item of a response the caller created; the item of another user’s response is “not found”.
  • Rows expire after OPEN_RESPONSES_STORE_TTL. With the TTL at 0 a database store applies a default of 7 days, because a table does not end with the process.

A running background response holds a lease in its row, which its owner renews every 15 seconds (the lease lasts 45 seconds). When the owner dies, for example because the pod is replaced, the lease runs out and the response is ended as failed with the error code server_restarted. A final response.failed event is added, so a client that resumes the stream gets every kept event and then the end. LocalAI does not run the request again: a generation cannot continue from a cut point, and tools may have had effects. Send the request again, with previous_response_id to keep the context. A standalone server ends the runs a previous process left when it starts. In distributed mode one frontend at a time runs the sweep.

POST /v1/responses/{id}/cancel sets a cancel_requested flag in the row. The owner checks it on every lease renewal, so a cancel works even if the bus message is lost. If the owner died before it could stop, the response ends as cancelled.

Tool Calling

Open Responses API supports function calling with tools:

curl http://localhost:8080/v1/responses \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ggml-koala-7b-model-q4_0-r2.bin",
    "input": "What is the weather in San Francisco?",
    "tools": [
      {
        "type": "function",
        "name": "get_weather",
        "description": "Get the current weather",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state"
            }
          },
          "required": ["location"]
        }
      }
    ],
    "tool_choice": "auto",
    "max_output_tokens": 1024
  }'

For streaming requests with JSON tool output, LocalAI waits for the complete JSON object before emitting a completed function_call item. Arguments can span multiple tokens. Read the arguments from the response.output_item.done event before executing the tool.

Reasoning Configuration

Configure reasoning effort and summary style:

curl http://localhost:8080/v1/responses \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ggml-koala-7b-model-q4_0-r2.bin",
    "input": "Solve this complex problem step by step",
    "reasoning": {
      "effort": "high",
      "summary": "detailed"
    },
    "max_output_tokens": 2048
  }'

Response Format

{
  "id": "resp_abc123",
  "object": "response",
  "created_at": 1234567890,
  "completed_at": 1234567895,
  "status": "completed",
  "model": "ggml-koala-7b-model-q4_0-r2.bin",
  "output": [
    {
      "type": "message",
      "id": "msg_001",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "This is a test!",
          "annotations": [],
          "logprobs": []
        }
      ],
      "status": "completed"
    }
  ],
  "error": null,
  "incomplete_details": null,
  "temperature": 0.7,
  "top_p": 1.0,
  "presence_penalty": 0.0,
  "frequency_penalty": 0.0,
  "usage": {
    "input_tokens": 10,
    "output_tokens": 5,
    "total_tokens": 15,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens_details": {
      "reasoning_tokens": 0
    }
  }
}

Backends

RWKV

RWKV support is available through llama.cpp (see below)

llama.cpp

llama.cpp is a popular port of Facebook’s LLaMA model in C/C++.

Note

The ggml file format has been deprecated. If you are using ggml models and you are configuring your model with a YAML file, specify, use a LocalAI version older than v2.25.0. For gguf models, use the llama backend. The go backend is deprecated as well but still available as go-llama.

Features

For the llama-server options you can set on a model, and for pasting a llama-server command into the model editor, see Engine runtime settings.

The llama.cpp model supports the following features:

Setup

LocalAI supports llama.cpp models out of the box. You can use the llama.cpp model in the same way as any other model.

Manual setup

It is sufficient to copy the ggml or gguf model files in the models folder. You can refer to the model in the model parameter in the API calls.

You can optionally create an associated YAML model config file to tune the model’s parameters or apply a template to the prompt.

Prompt templates are useful for models that are fine-tuned towards a specific prompt.

With the llama.cpp backend, streaming and non-streaming chat requests preserve the template’s grammar, stop strings, and message boundaries.

Automatic setup

LocalAI supports model galleries which are indexes of models. For instance, the huggingface gallery contains a large curated index of models from the huggingface model hub for ggml or gguf models.

For instance, if you have the galleries enabled and LocalAI already running, you can just start chatting with models in huggingface by running:

curl http://localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{
     "model": "TheBloke/WizardLM-13B-V1.2-GGML/wizardlm-13b-v1.2.ggmlv3.q2_K.bin",
     "messages": [{"role": "user", "content": "Say this is a test!"}],
     "temperature": 0.1
   }'

LocalAI will automatically download and configure the model in the model directory.

Models can be also preloaded or downloaded on demand. To learn about model galleries, check out the model gallery documentation.

YAML configuration

To use the llama.cpp backend, specify llama-cpp as the backend in the YAML file:

name: llama
backend: llama-cpp
parameters:
  # Relative to the models path
  model: file.gguf

Backend Options

The llama.cpp backend supports additional configuration options that can be specified in the options field of your model YAML configuration. These options allow fine-tuning of the backend behavior:

OptionTypeDescriptionExample
use_jinja or jinjabooleanEnable Jinja2 template processing for chat templates. When enabled, the backend uses Jinja2-based chat templates from the model for formatting messages.use_jinja:true
context_shiftbooleanEnable context shifting, which allows the model to dynamically adjust context window usage.context_shift:true
cache_ramintegerSize budget in MiB for the server-side prompt cache (a host-RAM store of idle slot KV states that’s reloaded on a prompt-prefix hit, see upstream PR #16391). Default: 8192 MiB (llama.cpp default). -1 removes the limit. 0 disables the prompt cache entirely. Together with kv_unified and cache_idle_slots this is what makes a repeated system prompt skip prefill on subsequent calls.cache_ram:4096
slot_save_pathstringDirectory where the slot save and restore API writes and reads prompt-cache files. Save and restore are off unless this is set. LocalAI creates the directory with mode 0700 if it is missing. See Saving and restoring a prompt cache.slot_save_path:/var/lib/localai/slots
parallel or n_parallelintegerEnable parallel request processing. When set to a value greater than 1, enables continuous batching for handling multiple requests concurrently.parallel:4
grpc_servers or rpc_serversstringComma-separated list of gRPC server addresses for distributed inference. Allows distributing workload across multiple llama.cpp workers.grpc_servers:localhost:50051,localhost:50052
fit_params or fitbooleanEnable auto-adjustment of model/context parameters to fit available device memory. Default: true.fit_params:true
fit_params_target or fit_targetintegerTarget margin per device in MiB when using fit_params. Default: 1024 (1GB).fit_target:2048
fit_streamstringWhat to do when the weights that stay in system memory do not fit in the available RAM: auto (default) loads them from the mapped model file as needed (slow, reads the disk, but runs), on always does, off refuses the load (“model does not fit in memory and disk streaming is disabled”) instead of paging from disk. With auto or on the backend also reserves a MoE expert cache and fits again when experts stay in system memory and moe_cache_mib is not set. When it streams a MoE model with a GPU, the routed experts stay in the model file: a small host tier of the MoE cache (moe_cache_host_mib) and the GPU cache hold the experts in use, and prompts are read in ubatches of up to 4096 tokens (switch localai_moe_stream, see MoE streaming). The default of the instance is the environment variable LOCALAI_FIT_STREAM; this option wins over it. Streaming only reads the model file and never writes to the disk. The model editor has it as Disk streaming in the Memory group. See GPU auto-fit.fit_stream:off
fit_params_min_ctx or fit_ctxintegerMinimum context size that can be set by fit_params. Default: 4096.fit_ctx:2048
n_cpu_ffnintegerKeep the dense FFN weights of the first N layers on the CPU (upstream --n-cpu-ffn), the counterpart of n_cpu_moe for dense models. Default: 0.n_cpu_ffn:12
yarn_orig_ctxintegerOriginal context size of the model for YaRN scaling (upstream --yarn-orig-ctx). 0 uses the model’s training context size.yarn_orig_ctx:32768
moe_cache_mibintegerSize in MiB of a GPU cache for MoE expert weights that stay in host memory (upstream --moe-cache-mib). Off by default (0). It helps only when experts are in host memory, with cpu_moe, n_cpu_moe or a fit_params spill. The cache uses GPU memory, so lower gpu_layers or the fit result may change. Experimental upstream. A cache that is too small can thrash, because every token evicts its own experts. A rough starting point is about 10% of the total expert size.moe_cache_mib:4096
moe_cache_host_mibintegerHost tier of the MoE cache in MiB (upstream --moe-cache-host-mib, LocalAI patch 0080): the routed expert weights are not loaded, they stay in the model file and are read into this much pinned RAM when the router selects them, then uploaded to the GPU cache. Needs moe_cache_mib (or the cache fit_stream reserves). Off by default (0). fit_stream turns it on and sizes it by itself when it streams a MoE model with a GPU, so set it only to force a size. It only reads the model file.moe_cache_host_mib:2048
moe_cache_cpu_sharefloatShare of the MoE cache misses that the CPU computes from the host experts instead of uploading them to the GPU once the cache is full, from 0 to 1 (upstream --moe-cache-cpu-share). Default 0: every miss is uploaded. It applies only when the cache is on (moe_cache_mib > 0). Values outside 0 to 1 are ignored with a warning. The best value depends on the hardware. In the upstream tests a small cache did best with a high share and a large cache with a low one. Upstream ships scripts/moe-cache-tune.py, which wraps a plain llama-server command, to find both values.moe_cache_cpu_share:0.5
n_cache_reuse or cache_reuseintegerMinimum chunk size to attempt reusing from the cache via KV shifting. Default: 0 (disabled).cache_reuse:256
slot_prompt_similarity or spsfloatHow much the prompt of a request must match the prompt of a slot to use that slot. Default: 0.1. Set to 0 to disable.sps:0.5
swa_fullbooleanUse full-size SWA (Sliding Window Attention) cache. Default: false.swa_full:true
cont_batching or continuous_batchingbooleanEnable continuous batching for handling multiple sequences. Default: true.cont_batching:true
check_tensorsbooleanValidate tensor data for invalid values during model loading. Default: false.check_tensors:true
warmupbooleanEnable warmup run after model loading. Default: true.warmup:false
no_op_offloadbooleanDisable offloading host tensor operations to device. Default: false.no_op_offload:true
device or devicesstringSelect the llama.cpp backend devices to use. Repeat the option or pass a comma-separated list; unlisted devices are excluded. Use the names reported by llama-server --list-devices / --list-devices.devices:CUDA1,CUDA2,CUDA3
kv_unified or unified_kvbooleanUse a single unified KV buffer shared across all sequences. Default: true (LocalAI override; upstream defaults to false but auto-enables it when slot count is auto). Required for cache_idle_slots and scoring: without it the server force-disables idle-slot saving at init, and score-enabled models are rejected at load time.kv_unified:false
kv_unified_per_slotintegerContext limit per parallel slot (upstream --kv-unified-per-slot). When context_size is not set, the shared KV cache is sized to parallel times this value. Default: unset.kv_unified_per_slot:8192
paged_kv or paged_servingbooleanPaged serving: the slots share one KV pool, requests start only when the pool has room, and a request is preempted when it runs out. See Paged serving. Default: true; paged_kv:false turns it off.paged_kv:false
kv_pool_tokensintegerTotal size of the shared KV pool in tokens. Sets the context size. Default: context_size.kv_pool_tokens:32768
prefill_budget or max_prefill_tokensinteger or autoPrompt tokens read per step while other requests generate, so a long prompt does not stall them. auto adapts it to the number of decoding streams. An explicit value works with or without paged_kv. 0 turns it off. Default: auto with paged serving, 0 (off, as in upstream llama.cpp) with paged_kv:false.prefill_budget:512
prefill_longintegerThe prefill budget holds back only prompts longer than this many tokens; shorter prompts are read whole. 0 holds back every prompt. Default: 1024.prefill_long:0
kv_output_reserveintegerFree cells a request needs beyond its prompt before it starts, capped at its max tokens. Only with paged_kv. Default: 256.kv_output_reserve:512
paged_preemptbooleanWith paged serving, preempt a request when the pool runs out, and resume it later. Default: true. Not recommended to turn off: with paged_preempt:false a pool that overflows fails every in-flight stream with HTTP 500 “Context size has been exceeded”.paged_preempt:false
spec_max_streamsintegerSpeculative drafting pauses while more than this many streams decode, and resumes when the count drops by a quarter (at least one). 0 never pauses. Default: when spec_mode is auto (the default), 1 for MTP and 0 for the other drafters, which Automatic already switches per number of streams; with adaptive or fixed, 4. Set a higher number to let more requests draft with MTP, or spec_mode:off to stop drafting.spec_max_streams:8
spec_modestringDraft mode for a model with a drafter. auto (Automatic, the default): the server chooses among plain decoding, drafts of spec_n_max tokens and drafts of half of that, and keeps the fastest for the current load. It measures the step time of each choice and the acceptance of the current requests while it serves; in plain decoding one request at a time drafts a short sample now and then. The drafter rests in plain decoding: a draft model catches up on the last 256 tokens before it drafts again, and an MTP, EAGLE3 or DFlash drafter reads 32 batches first. adaptive: always draft, and pick each draft length from the measured acceptance and step time, up to spec_n_max. fixed: always draft spec_n_max tokens. off: do not draft. A spec_max_streams set in the model still pauses drafting first.spec_mode:fixed
spec_adaptivebooleanOlder form of spec_mode: true is adaptive and false is fixed. spec_mode wins when both are set.spec_adaptive:false
localai_mmq_stream_k_orderbooleanSwitch of LocalAI’s llama.cpp patch 0010 (NVIDIA CUDA): MMQ matrix multiplications with more tiles than GPU blocks walk the column tiles outermost, 2% to 13% faster prompt processing at micro-batch 256 and 512 on GB10. Published runs on discrete cards show losses. Sets LLAMA_LOCALAI_MMQ_STREAM_K_ORDER before the model loads, unless it is already set. Unset, it runs only on GB10; true runs it on every NVIDIA GPU; false runs the upstream code everywhere.localai_mmq_stream_k_order:false
localai_fa_ncols2booleanSwitch of LocalAI’s llama.cpp patch 0012 (NVIDIA CUDA): from 32 tokens up, flash attention picks the tile width that pads the attention head groups least, 11% to 13% faster prompt processing for Qwen3-14B on GB10. Its author reports slower cases on a discrete card. Sets LLAMA_LOCALAI_FA_NCOLS2 before the model loads, unless it is already set. Unset, it runs only on GB10; true runs it on every NVIDIA GPU; false runs the upstream code everywhere.localai_fa_ncols2:false
localai_pdl_stagebooleanSwitch of LocalAI’s llama.cpp patch 0014 (NVIDIA CUDA, Hopper and newer): the quantized mat-vec kernel prefetches its weights into L2 before it waits for the previous kernel. Decode 3% to 14% faster on GB10 and about 6% on Thor. Sets LLAMA_LOCALAI_PDL_STAGE before the model loads, unless it is already set. Default: true.localai_pdl_stage:false
localai_mmq_few_startbooleanSwitch of LocalAI’s llama.cpp patch 0015 (NVIDIA GB10 and Thor): with 2 to 8 tokens in a step, quantized matmuls move from the mat-vec kernel to the few-row MMQ kernel at the column count that measured fastest on each GPU. On GB10 Qwen3-8B and Llama-3.1-8B Q4_K_M decoded 4% faster with 2 streams, on Thor 12% faster with 2 streams and 28% with 3. Sets LLAMA_LOCALAI_MMQ_FEW_START before the model loads, unless it is already set. Default: true.localai_mmq_few_start:false
localai_moe_group_smallbooleanSwitch of LocalAI’s llama.cpp patch 0016 (NVIDIA CUDA): MoE models with 2 to 8 tokens in a step read each expert once for all the tokens routed to it. Sets LLAMA_LOCALAI_MOE_GROUP_SMALL before the model loads, unless it is already set. Unset, it runs only for MXFP4 and Q5_0 experts on GB10, where it measured 6.5% to 12.3% faster; true runs it for every supported type on every GPU, which was slower on Thor; false runs the upstream code everywhere.localai_moe_group_small:false
localai_drop_page_cachebooleanSwitch of LocalAI’s llama.cpp patch 0020 (Linux, GPU that shares memory with the CPU, such as NVIDIA GB10, Thor and Orin): the page cache copy of the model file is dropped while the model loads, so the weights take their memory once. Decode speed does not change; loading the same model again reads the file from disk. Sets LLAMA_LOCALAI_DROP_PAGE_CACHE before the model loads, unless it is already set. Default: true.localai_drop_page_cache:false
localai_fast_samplebooleanSwitch of LocalAI’s llama.cpp patch 0021 (every backend): sampling takes the largest logits straight from the output row instead of building and sorting a candidate list over the whole vocabulary, with the same sampled tokens. Decode 2.7% to 3.8% faster on GB10 with Qwen3-8B. Sets LLAMA_LOCALAI_FAST_SAMPLE before the model loads, unless it is already set. Default: true.localai_fast_sample:false
localai_graph_arenasbooleanSwitch of LocalAI’s llama.cpp patch 0022 (every backend), a backport of ggml-org/llama.cpp#31156: decode and speculative verify steps keep the graph of each batch shape (up to 16 to 64 shapes) instead of rebuilding it whenever the number of streams or drafted tokens changes. With a draft model, decode 5% to 8% faster on GB10 with Qwen3-8B. Sets LLAMA_LOCALAI_GRAPH_ARENAS before the model loads, unless it is already set. Default: true.localai_graph_arenas:false
localai_split_gatebooleanSwitch of LocalAI’s llama.cpp patch 0024 (NVIDIA CUDA and AMD ROCm (not RDNA)), from ggml-org/llama.cpp#33019: with short rows the mat-vec kernel reads the gate weights in a loop of their own. Unset, it runs only on Jetson Thor, where decode of Qwen2.5 1.5B and 3B was 3% to 4% faster; no change on GB10; the pull request reports 11% to 21% on an RTX 3060, not measured by LocalAI; true runs it on every such GPU and false runs the upstream code everywhere. Sets LLAMA_LOCALAI_SPLIT_GATE before the model loads, unless it is already set.localai_split_gate:false
localai_small_k_inclusivebooleanSwitch of LocalAI’s llama.cpp patch 0025 (NVIDIA CUDA and AMD ROCm (not RDNA)), from the first revision of ggml-org/llama.cpp#33019: rows exactly at the short-row limit also take the short-row mat-vec kernel. Unset, it runs only on Jetson Thor, where decode of Qwen2.5-3B Q4_K_M was 18% faster and of OLMoE 7% faster; it was 1% to 3% slower on GB10; true runs it on every such GPU and false runs the upstream code everywhere. Sets LLAMA_LOCALAI_SMALL_K_INCLUSIVE before the model loads, unless it is already set.localai_small_k_inclusive:false
localai_rdna35_q6k_mmqbooleanSwitch of LocalAI’s llama.cpp patch 0040 (AMD ROCm, RDNA3.5): Q6_K weights with 257 to 512 prompt tokens use the quantized matmul kernel instead of a dequantize and a hipBLAS matmul. Prompt processing 8.7% to 10.1% faster for a Q6_K 8B model on Strix Halo. Sets LLAMA_LOCALAI_RDNA35_Q6K_MMQ before the model loads, unless it is already set. Default: true.localai_rdna35_q6k_mmq:false
localai_rdna35_fa_wmma_nogqabooleanSwitch of LocalAI’s llama.cpp patch 0041 (AMD ROCm, RDNA3.5): models without grouped-query attention, such as OLMoE, run prompt attention on the WMMA flash attention kernel. Prompt processing 2% to 6% faster for OLMoE on Strix Halo. Sets LLAMA_LOCALAI_RDNA35_FA_WMMA_NOGQA before the model loads, unless it is already set. Default: true.localai_rdna35_fa_wmma_nogqa:false
localai_metal_moe_fewrowbooleanSwitch of LocalAI’s llama.cpp patch 0070 (Apple Metal): tokens routed to the same Q8_0 expert share one read of its weights. Sets LLAMA_LOCALAI_METAL_MOE_FEWROW before the model loads, unless it is already set. Default: true. See LocalAI speed patches.localai_metal_moe_fewrow:false
localai_metal_fa_gqabooleanSwitch of LocalAI’s llama.cpp patch 0071 (Apple Metal): decode attention reads each K/V element once per GQA group from a KV of 4096 tokens. Sets LLAMA_LOCALAI_METAL_FA_GQA before the model loads, unless it is already set. Default: true.localai_metal_fa_gqa:false
localai_moe_streambooleanSwitch of LocalAI’s llama.cpp patches 0082 and 0083 (MoE streaming engine): when fit_stream streams a MoE model with a GPU, the experts stay in the model file behind the tiers of the MoE cache, and prompts read each expert once per 4096-token ubatch with several threads. false streams the whole mapping as before. Sets LLAMA_LOCALAI_MOE_STREAM before the model loads, unless it is already set. Default: true.localai_moe_stream:false
localai_moe_prefetchbooleanSwitch of LocalAI’s llama.cpp patch 0084 (MoE streaming read-ahead): while one layer of a streamed MoE model reads a prompt, the experts of the next layer that it used most are read from the disk into 384 MiB of host memory that fit_stream takes from the device tier. Same output. Unset reads ahead when the disk can do it in the time the layer computes and the device tier has room; true reads ahead always; false reads each expert when the layer needs it. Sets LLAMA_LOCALAI_MOE_PREFETCH before the model loads, unless it is already set. Default: unset.localai_moe_prefetch:false
admission_orderbooleanWith paged serving, waiting requests go by priority class (with aging), then fewest prompt tokens not covered by a cache, then arrival, with an overtake cap; false keeps first come, first served. Default: true.admission_order:false
prefill_capintegerWith paged serving, the most prompt tokens one request reads per step while other requests read prompts too; a request alone gets the whole step. 0 turns it off. Default: 512.prefill_cap:0
slot_attach or prefix_attachbooleanWith paged serving, a request whose prompt starts with what another slot holds (busy or idle, at least 256 tokens) shares those KV cells instead of reading them again. Default: true.slot_attach:false
cache_idle_slots or idle_slots_cachebooleanOn a new task, save the previous slot’s KV state into the prompt cache (and clear the slot) so a later request with the same prefix can warm-load it. Default: true. Auto-disabled by the server if kv_unified=false or cache_ram=0.cache_idle_slots:false
n_ctx_checkpoints or ctx_checkpointsintegerMaximum number of context checkpoints per slot (used for partial-prefix recovery, e.g. SWA). Default: 32.ctx_checkpoints:16
checkpoint_min_step or checkpoint_min_spacing (aliases: checkpoint_every_nt, checkpoint_every_n_tokens)integerMinimum spacing in tokens between context checkpoints. 0 disables the minimum-spacing gate. Default: 256. (Renamed upstream from checkpoint_every_nt; semantics shifted from a fixed cadence to a minimum spacing.)checkpoint_min_step:1024
split_mode or smstringHow to split the model across multiple GPUs: none (single GPU only), layer (default - split layers and KV across GPUs), row (deprecated upstream; use tensor), tensor (experimental tensor parallelism: each layer is split across all GPUs for lower token latency). tensor needs flash attention (flash_attention: "on", or "auto", which llama.cpp turns on in this mode), fit_params:false and a context_size you set yourself, and it is not implemented for every architecture. Quantized KV cache (cache_type_k/cache_type_v) works with it on the bundled llama.cpp (#23792); f16 is the safe choice. The NVIDIA CUDA backends ship NCCL for the GPU-to-GPU reductions. See the tensor split configuration.split_mode:tensor
backend_sampling or gpu_samplingstringWhere tokens are sampled: off (default, on the CPU), on (on the device that holds the output, such as the GPU) or auto (decided per request). true/false and 1/0 also work. See Backend sampling below.backend_sampling:auto
backend_sampling_min_slotsintegerWith backend_sampling:auto, the number of requests that must run at the same time before a request samples on the GPU. Default: 16.backend_sampling_min_slots:8
grammar_enginestringEngine of the grammars that LocalAI builds from a JSON schema (response_format and tool calls): auto (default), gbnf or llguidance. See Grammar engine below.grammar_engine:gbnf
grammar_max_repetitionintegerLimit of the GBNF repetition check. llama.cpp stops at 2000, which the grammar of a large tool set exceeds: the request then fails with “number of rules that are going to be repeated … exceeds sane defaults”. Default: 100000. The LLAMA_GRAMMAR_MAX_REPETITION environment variable sets it for every model when the option is not set.grammar_max_repetition:20000

Example configuration with options:

name: llama-model
backend: llama
parameters:
  model: model.gguf
options:
  - use_jinja:true
  - context_shift:true
  - cache_ram:4096
  - parallel:2
  - devices:CUDA1,CUDA2,CUDA3
  - fit_params:true
  - fit_target:1024
  - slot_prompt_similarity:0.5

Note: The parallel option can also be set via the LLAMACPP_PARALLEL environment variable, and grpc_servers can be set via the LLAMACPP_GRPC_SERVERS environment variable. Options specified in the YAML file take precedence over environment variables.

fit_stream can be set for the whole instance with the environment variable LOCALAI_FIT_STREAM (off, auto or on); the option of a model wins.

An explicit parallel: 1 (or n_parallel: 1) in the model options takes precedence over LLAMACPP_PARALLEL, like any other value. The environment variable is only used when neither option is set; if it is missing or not a number, the backend uses 8 slots with paged serving (the default) and one slot without it.

Backend sampling

By default llama.cpp copies the logits of every slot to the host after each decode step and samples the slots one after the other on the CPU. With backend sampling (upstream --backend-sampling, ggml-org/llama.cpp#25532) the sampler chain runs on the device that holds the output, so the copy goes away and the slots are sampled in parallel. The gain grows with the number of slots that decode together: one stream gains little, many concurrent streams gain the most. The feature is experimental upstream and is off by default.

  • backend_sampling:on asks for backend sampling on every request.
  • backend_sampling:auto decides per request. A request samples on the backend only when all of these hold: the model is offloaded to a GPU (a GPU device is present and gpu_layers is not 0), split_mode is not tensor, the request has no grammar (no JSON schema, no response_format grammar, no tool-call grammar), no reasoning-budget sampler and no logprobs, and at least backend_sampling_min_slots requests (default 16) are running, this one included. The decision is made when the request starts and holds for its whole generation.
  • backend_sampling:off keeps sampling on the CPU. A raw --backend-sampling flag in options still turns it on.

Measured on a GB10 (DGX Spark) with Qwen3-8B: backend_sampling:on was neutral at 1 and 8 decoding streams and gave 2.5% more throughput at 12, 6.5% at 16 and 10% at 32, with the inter-token latency p99 25 to 40 ms higher. auto with 16 slots behind LocalAI was slower than off: about 16 requests in flight gave 277 against 300 tok/s and an inter-token latency p99 of 363 against 110 ms, because one batch then mixes requests sampled on the GPU and on the CPU. Use on for a model that serves many concurrent requests, and keep off (the default) otherwise.

llama.cpp turns backend sampling off for a request by itself when the request uses a grammar, a reasoning budget (thinking models with tool calls) or logprobs taken before sampling, and for text-to-speech; auto leaves those requests on the CPU from the start. Only a prefix of the sampler chain made of top-k, top-p, min-p, temperature, penalties, logit bias and the final draw runs on the device; other samplers (typical-p, XTC, mirostat, DRY) run on the CPU.

Known upstream issues at the time of writing: #32141 (min_keep and min_p handling), #31840 (pinned host buffers are allocated again each time a request ends) and #32637 (an invalid token on Metal with a small vocabulary). Test greedy output against off before you turn it on for a model.

Grammar engine

LocalAI constrains the output of the model with a grammar for JSON mode (response_format with a json_schema) and for tool calls when it builds the tool-call grammar itself. llama.cpp has two engines for these grammars:

  • GBNF: the grammar sampler of llama.cpp. It works in every build. It can be slow on a large schema, such as a big tool set, and llama.cpp rejects a grammar whose repetitions expand too far.
  • llguidance: a Rust engine that takes the JSON schema directly. It computes the allowed tokens faster on large schemas and supports more of JSON Schema. The llama.cpp backend images for Linux and macOS are built with it.

The grammar_engine option selects the engine:

ValueBehavior
auto (default)Use llguidance for the grammars LocalAI builds when the backend build has it, GBNF otherwise. The tool-call grammars of the chat template use GBNF.
gbnfAlways use GBNF, exactly as upstream llama.cpp.
llguidanceUse llguidance, also for the tool-call grammars of the chat template (see below). A build without it logs a warning and uses GBNF.
options:
  - grammar_engine:gbnf

These grammars always use GBNF:

  • a grammar you write yourself (the grammar request field or the grammar key of the model config),
  • response_format of type json_object,
  • function calling with mixed_mode: true (free text or JSON) or schema_type: llama3.1.
Tool-call grammars of the chat template

When llama.cpp parses tool calls itself (grammar.disable: true with use_tokenizer_template: true), it builds a GBNF grammar from the chat template of the model. With grammar_engine:llguidance, the backend translates that grammar to llguidance when the request starts. It is the same grammar, for every template: no format has its own rules.

  • Speed. On GBNF, the cost of the allowed-token mask grows with the tool set, to tens of milliseconds per token with 48 or 128 tools. On llguidance it stays below about 1 ms. The backend first checks the token the model picked and computes the full mask only when that token is rejected, so text outside a tool call costs almost nothing.
  • Large tool sets. GBNF rejects some large schemas, for example an array with maxItems: 2000 or hundreds of optional properties (“exceeds sane defaults”, “chained more than 256 levels deep”). llguidance accepts them.
  • Fallback. If the grammar does not translate or llguidance rejects it, the request uses GBNF and the backend logs one warning. If llguidance fails during generation, or rejects a token that GBNF accepts, the request goes on with GBNF from that point. The output is never left without a grammar because of llguidance.
  • Lazy grammars. Most templates constrain the output only after a trigger such as <tool_call>. The trigger rules are the same as on GBNF.

Under auto, these grammars stay on GBNF for now. To go fully stock, set grammar_engine:gbnf: every grammar then uses llama.cpp’s GBNF sampler, as upstream.

With llguidance (any grammar, also the JSON-schema grammars above), tokens that a model adds to its vocabulary, such as <tool_call> in Qwen, count as special tokens: the grammar matches them by token, not by text. As a result, such a token cannot appear inside a JSON string of the output as one token; the model can still write the same characters with ordinary tokens.

With llguidance, an object in the schema that has no required list requires all its properties, and an object without additionalProperties allows no other property, as with the GBNF grammar of LocalAI. A required list and additionalProperties that the schema sets are kept, and keywords such as minLength, pattern and maxItems, which the GBNF converter ignores, are enforced. Between two JSON tokens the model may write one space or none, as with the GBNF grammar.

Use gbnf when a model must behave exactly as before, for example when a prompt relies on whitespace that the GBNF grammar allows. Other backends ignore the option.

Hardware auto-tuning (and how to override it)

On a detected GPU, LocalAI fills a few performance-relevant defaults the model config leaves unset - a larger physical batch (2048) on NVIDIA GB10 (DGX Spark) and Jetson Thor, and a VRAM-scaled parallel slot count for concurrent serving. Both are gated on per-device VRAM at the model’s context: when a large context already fills a single card (e.g. a 27B model with a 200k context across 2×16 GiB), the batch boost and the extra parallel slots are suppressed so they can’t tip the tighter GPU into CUDA out-of-memory.

The larger batch needs a GPU that shares the system memory, as GB10 and Thor do: it was measured there. A Blackwell card with its own memory (RTX 50 series, RTX PRO) keeps the default batch of 512, because nobody measured the larger batch on one and its compute buffer comes out of the card’s VRAM. Set batch: 2048 in the model YAML to try it on such a card. In distributed mode the node’s reported memory kind decides.

Anything you set explicitly in the model YAML always wins, so to pin a value just set it (e.g. batch: 512 or options: ["parallel:1"]). The effective values are logged at INFO when a model loads (effective runtime tuning …). To turn the hardware auto-tuning off entirely and run llama.cpp’s stock behavior, set:

LOCALAI_DISABLE_HARDWARE_DEFAULTS=true
Paged serving

With parallel above 1, the slots of a model share one KV cache (kv_unified, on by default). Without scheduling, when more requests arrive than that cache holds, the server runs out of cells mid-generation and fails every running request with “Context size has been exceeded”. Paged serving, on by default, schedules the shared cache as a pool instead:

  • Admission. A request starts reading its prompt only when the pool has room for the prompt and its output reserve (kv_output_reserve), after what the running requests still need. Otherwise it waits in its slot, first come, first served. A waiting request holds no KV cells: its prompt cache entry is loaded when it is admitted.
  • Preemption. When the running requests outgrow the pool, one request is preempted: the one holding the fewest cells (the cheapest to recompute), the youngest on a tie. Its cells are freed, it waits ahead of newer requests, and when there is room for it plus some spare (twice kv_output_reserve, at least 256 cells) its tokens are computed again and it continues where it stopped. One request is preempted at most twice while another can be preempted instead. Keep preemption on: without it, a pool that overflows fails every in-flight stream with HTTP 500, and in a CPU benchmark with output lengths the clients did not declare, 25% to 67% of the requests failed; with it, all completed. The output does not change, apart from rare near ties in greedy decoding. Hybrid and recurrent models (Qwen3.5, LFM2, Granite-H) and speculative decoding with a draft model or MTP resume the same way: the recompute rebuilds the recurrent state and the draft’s cache too. A request that cannot be recomputed (an image or audio prompt, aLoRA) is preempted only when nothing else can be: its state is saved to a RAM stash, capped by cache_ram, and restored when there is room. Score requests are never preempted. If the stash is full (or cache_ram is 0), such a request fails with the retryable error “KV pool full, preempted; retry the request”.
  • Prefix sharing. A request whose prompt starts with the prompt of another request (a shared system prompt, the earlier turns of a conversation) starts from that slot’s KV cells, even while the other request is still generating: the shared part is neither copied nor computed again. It needs at least 256 shared tokens and is off for sliding-window, hybrid and recurrent models, multimodal prompts and draft models. slot_attach:false turns it off.
  • Drafting. Speculative drafting is off unless the model asks for it (a draft model, or spec_type:ngram-mod to draft from n-grams of the model’s own context) or the model file has an MTP head, which LocalAI turns on by itself. N-gram drafting speeds up repetitive output (code edits, lists, quoting the prompt) but on ordinary chat output it rarely finds a match: on a GB10 (DGX Spark) with Qwen3-8B it cost 3% on one stream and 6-7% at 32 streams. When drafting is on, it pauses while more than spec_max_streams streams decode, where batching pays more than drafting, and resumes when the count drops by a quarter. With spec_mode:auto (the default) MTP drafts for one stream at a time and pauses above it, and the other drafters do not pause: Automatic measures, for each number of streams, whether drafting is faster. With adaptive or fixed every drafter pauses above 4 streams. Set spec_max_streams to change the limit, or spec_mode:off to stop drafting.
  • Order of waiting requests. Requests that wait for a slot or for room in the pool go by priority class first (interactive chats before default API calls before batch work such as sub-agents, jobs and collection indexing; see service_tier), then by the prompt tokens no cache covers (cache hits and short prompts first), then by arrival. A request gains a class for every 20 s it waits, and goes by arrival once 8 later requests went first or it waited 30 s, so nothing starves. admission_order:false keeps first come, first served.
  • Idle slots. When the pool needs cells held by idle slots, the least recently used idle slot is saved to the RAM prompt cache and trimmed from the tail, only as much as needed (at least 256 cells). With lazy_idle_save:true, idle slots also skip the save-and-clear that happens after each new request and keep their cells until the pool needs them; it is off by default because in the GPU A/B it served fewer repeated prompts from the cache.
  • Prefill budget. prefill_budget limits how many prompt tokens a step reads while other requests generate. A long prompt then no longer stops the other streams for seconds. The default is auto: the budget follows the load, the whole batch (batch) while at most one stream decodes, then 2048 divided by the number of decoding streams, never below 128. auto counts only the streams that were already decoding when the oldest waiting long prompt arrived. So a long prompt that runs alone is read as fast as without a budget, and so is a burst of long prompts: the requests of the burst that finish their prompts first do not slow down the rest of the burst. Counting every decoding stream read a burst of 32 prompts of 4096 tokens in steps of 100 to 400 tokens, and each step paid the full fixed cost of a prompt step. A chat that arrives after the long prompt is not protected: it waits for the whole-batch steps of that prompt, as without a budget. The budget is a trade-off. On a GB10 (DGX Spark) with batch:2048 and a 32K-token prompt among active chats, the worst gap between two tokens of a chat was about 246 ms with the budget, against 809 ms for stock llama.cpp, which has no budget. The cost is the long prompt: in an earlier run it got its first token after 26.4 s against 11.5 s without the budget. Turn it off (prefill_budget:0) for throughput when nobody chats while long prompts are read. A number sets a fixed budget, which also caps a prompt that runs alone: on a GB10 with one 64K-token prompt and batch:2048, prefill_budget:256 gave 39% less prefill throughput than auto. Only prompts longer than prefill_long (default 1024 tokens) are held back: a burst of short prompts is read whole, as without a budget, because spreading it over budget-sized steps cost 4 to 5% of throughput and doubled the inter-token latency p99 in bursts of 16 and 32 requests, with no long prompt to protect the other streams from. prefill_long:0 applies the budget to every prompt. When the budget reads a prompt in several small steps, the server makes the context checkpoint near the end of the prompt once, plus the one 4 tokens before the end, as for a prompt read in whole batches. Before, models that need checkpoints (hybrid and recurrent models, sliding-window attention) made one in every small step. In the model editor, the llama.cpp serving section shows it as Keep other chats responsive while long prompts are read, with three choices: Default, On (auto) and Off (0). The Default choice shows what it resolves to, as Default (On) or Default (Off): what the loaded model reported, or else the default of this release, and always off while paged serving is off. While it is on, a tokens per step box for experts sets a fixed budget. With paged_kv:false the budget is off unless the model sets prefill_budget, so the server reads prompts like upstream llama.cpp.

To turn it off for one model:

options:
  - paged_kv:false      # no admission control or preemption, and no prefill budget

A model that sets the pool and the slots explicitly:

name: qwen3-8b
backend: llama-cpp
context_size: 32768   # the shared pool; or set kv_pool_tokens
parameters:
  model: Qwen3-8B-Q4_K_M.gguf
options:
  - parallel:16
  - prefill_budget:512

Notes:

  • When parallel is not set in the options or in LLAMACPP_PARALLEL, paged serving uses 8 slots and logs it. The KV cache does not grow with the slots: they share context_size. On a GPU, LocalAI’s hardware defaults set parallel from the VRAM, and set parallel:1 on a GPU without room for more slots, so a tight fit keeps one slot.
  • Each slot keeps a little state of its own: the sampler, and for hybrid and recurrent models (Qwen3.5, Granite-H, Nemotron-H, LFM2) a recurrent state and up to n_ctx_checkpoints copies of it (context checkpoints, in host memory). For such a model LocalAI reads the state size from the GGUF header and:
    • sets n_ctx_checkpoints so the checkpoints of all slots stay within the smaller of cache_ram (8 GiB by default) and a quarter of the host memory: slots x state x checkpoints, between 4 and 32 per slot. For example 6 for Qwen3.8-27B or Granite-4.0-H-Small at 8 slots, 20 for Qwen3.5-9B, and the default 32 for small models;
    • on a GPU, counts one state per slot in the headroom check that picks the default parallel, so a tight fit gets fewer slots. An explicit n_ctx_checkpoints or parallel always wins.
  • A model that sets kv_unified:false, context_shift:true or cont_batching:false runs without paged serving, with one info line in the log. Only paged_kv:true set explicitly together with one of those options fails the load, with an error that names the option.
  • A purely recurrent model (Mamba, RWKV) has no KV pool to share, so paged serving turns itself off for it at load, with one info line. Hybrid models (attention plus recurrent layers) keep it.
  • Embedding and rerank models run with paged serving too: their requests need no output reserve, and admission only waits when the pool is full.
  • parallel is the limit of requests in flight, waiting or running. Each slot can use the whole pool unless kv_unified_per_slot caps it.
  • The backend logs every admission wait (waits = N), every preemption (preemptions = N), how long a preempted request waited (resuming after waiting), and every last-resort abort (aborts = N).
  • Builds of the forks that do not carry LocalAI’s llama.cpp patches (for example turboquant) run without paged serving; they warn only when a model sets paged_kv:true or prefill_budget.
Server-side prompt cache (repeated system prompts)

Agents, coding assistants, and Anthropic/OpenAI-compatible CLIs typically resend the same large system prompt on every turn. The llama.cpp server can short-circuit prefill for the matching prefix by stashing idle slot KV states in host RAM and reloading them on a hit. Three settings interact:

SettingDefaultRole
cache_ram:N8192 (llama.cpp default)Allocates the host-side prompt cache. 0 disables it.
kv_unified:truetrueSingle unified KV buffer (prerequisite for idle-slot saving).
cache_idle_slots:truetruePersists the idle slot’s KV into the prompt cache on task switch.

All three are on by default since LocalAI v4.3, so the prompt cache works out of the box for the common single-slot setup. If you’re on an older release, or you’ve explicitly disabled one of them, add the following to recover the behaviour:

options:
  - cache_ram:4096       # or -1 for no limit
  - kv_unified:true
  - cache_idle_slots:true

Set cache_ram:0 to opt out of the prompt cache entirely (saves host RAM at the cost of re-prefilling repeated prompts).

cache_ram:-1 removes the limit. With idle-slot saving on, every distinct prompt then leaves its slot state in host RAM, so a workload with many different prompts (classification, ingestion) grows the backend by roughly the KV size of each prompt until the host runs out of memory.

Saving and restoring a prompt cache

The server-side prompt cache lives in RAM and is lost when the model unloads. To keep the prompt state of one slot on disk, set slot_save_path and use the slot API. A typical use is a voice assistant with a long system prompt: save the state once, then restore it when the wake word fires, so the first request does not wait for prefill.

options:
  - slot_save_path:/var/lib/localai/slots

Both calls need an admin API key when authentication is on. Without slot_save_path they return 400.

The server chooses the name of every saved file. A save returns an id, and a restore takes that id. A client cannot pick a file name or a path.

# Save slot 0 of the model. The reply contains the id.
curl http://localhost:8080/v1/slots/save \
  -H "Content-Type: application/json" \
  -d '{"model": "my-model", "slot": 0}'

# Load that state back into slot 0
curl http://localhost:8080/v1/slots/restore \
  -H "Content-Type: application/json" \
  -d '{"model": "my-model", "slot": 0, "id": "0123456789abcdef0123456789abcdef"}'
FieldDescription
modelName of a llama-cpp model.
slotSlot id. Default 0. With parallel:N the ids are 0 to N-1.
idRestore only. The id that a save returned for this model: 32 lowercase hex characters. Do not send it on save.

The save reply gives the id, the slot, the number of tokens and bytes, and the time taken in duration_ms. The message field lists the IDs of any older saves that were deleted to make room. The restore reply has the same fields. Neither reply contains a path on the host.

Keep these points in mind:

  • A client cannot choose names. The backend creates a directory for each model under slot_save_path (mode 0700) and writes a manifest.json in it. A restore works only for an id in the manifest of that model. Any other id returns 404 with no saved state with this id for this model.
  • The backend keeps at most 32 saves for each model. When a save would go over that, it deletes the oldest one and lists its id in message. A save larger than 8 GiB is deleted and fails.
  • A restore also checks that the file is a plain file and has the size that was recorded at save time. A file that was replaced or cut short is refused.
  • Keep slot_save_path private to the user that runs LocalAI. LocalAI creates it with mode 0700 when it is missing, and writes a warning to the log when an existing directory is open to other users. The checks above cannot stop a local user who can write to the directory.
  • A saved state is only as fresh as its save. To change the cached prompt, save again and use the new id.
  • A saved state holds the prompt state for the model and quantisation it came from. Do not restore it into a different model, quantisation or context size. The restore call fails if the state does not fit, but a state from another model is not always detected.
  • A slot that is busy with a request is served after that request ends.
  • The API is for llama-cpp only. Other backends return 501.
Disk prompt cache

The RAM prompt cache is lost when the model unloads. The disk prompt cache keeps the state of long prompts (1,024 tokens or more, seen in at least two requests) on disk, per user, so a reload does not compute them again. It is on by default; prompt_cache_disk:false in options: turns it off for one model. See Disk Prompt Cache for the options, the sizes and the retention.

Reference

ik_llama.cpp

ik_llama.cpp is a hard fork of llama.cpp by Iwan Kawrakow that focuses on superior CPU and hybrid GPU/CPU performance. It ships additional quantization types (IQK quants), custom quantization mixes, Multi-head Latent Attention (MLA) for DeepSeek models, and fine-grained tensor offload controls - particularly useful for running very large models on commodity CPU hardware.

Note

The ik-llama-cpp backend requires a CPU with AVX2 support. The IQK kernels are not compatible with older CPUs.

Features

The ik-llama-cpp backend supports the following features:

Setup

The backend is distributed as a separate container image and can be installed from the LocalAI backend gallery, or specified directly in a model configuration. GGUF models loaded with this backend benefit from ik_llama.cpp’s optimized CPU kernels - especially useful for MoE models and large quantized models that would otherwise be GPU-bound.

YAML configuration

To use the ik-llama-cpp backend, specify it as the backend in the YAML file:

name: my-model
backend: ik-llama-cpp
parameters:
  # Relative to the models path
  model: file.gguf

The aliases ik-llama and ik_llama are also accepted.

Flash attention is on by default, as in ik_llama.cpp itself. ik_llama.cpp has no automatic mode, so flash_attention: auto (the value LocalAI uses when the key is not set) and on turn it on, and off turns it off. A quantized V cache (cache_type_v) needs it on.

Reference

turboquant (llama.cpp fork with TurboQuant KV-cache)

llama-cpp-turboquant is a llama.cpp fork that adds the TurboQuant KV-cache quantization scheme. It reuses the upstream llama.cpp codebase and ships as a drop-in alternative backend inside LocalAI, sharing the same gRPC server sources as the stock llama-cpp backend - so any GGUF model that runs on llama-cpp also runs on turboquant.

You would pick turboquant when you want smaller KV-cache memory pressure (longer contexts on the same VRAM) or to experiment with the fork’s quantized KV representations on top of the standard cache_type_k / cache_type_v knobs already supported by upstream llama.cpp.

Features

  • Drop-in GGUF compatibility with upstream llama.cpp.
  • TurboQuant KV-cache quantization (see fork README for the current set of accepted cache_type_k / cache_type_v values).
  • Same feature surface as the llama-cpp backend: text generation, embeddings, tool calls, multimodal via mmproj.
  • Available on CPU (AVX/AVX2/AVX512/fallback), NVIDIA CUDA 12/13, AMD ROCm/HIP, Intel SYCL f32/f16, Vulkan, and NVIDIA L4T.

Setup

turboquant ships as a separate container image in the LocalAI backend gallery. Install it like any other backend:

local-ai backends install turboquant

Or pick a specific flavor for your hardware (example tags: cpu-turboquant, cuda12-turboquant, cuda13-turboquant, rocm-turboquant, intel-sycl-f16-turboquant, vulkan-turboquant).

YAML configuration

To run a model with turboquant, set the backend in your model YAML and optionally pick quantized KV-cache types:

name: my-model
backend: turboquant
parameters:
  # Relative to the models path
  model: file.gguf
# Use TurboQuant's own KV-cache quantization schemes. The fork accepts
# the standard llama.cpp types (f16, f32, q8_0, q4_0, q4_1, q5_0, q5_1)
# and adds three TurboQuant-specific ones: turbo2, turbo3, turbo4.
# turbo3 / turbo4 auto-enable flash_attention (required for turbo K/V)
# and offer progressively more aggressive compression.
cache_type_k: turbo3
cache_type_v: turbo3
context_size: 8192

The cache_type_k / cache_type_v fields map to llama.cpp’s -ctk / -ctv flags. The stock llama-cpp backend only accepts the standard llama.cpp types - to use turbo2 / turbo3 / turbo4 you need this turboquant backend, which is where the fork’s TurboQuant code paths actually take effect. Pick q8_0 here and you’re just running stock llama.cpp KV quantization; pick turbo* and you’re running TurboQuant.

Reference

olala (llama.cpp fork for the Olala models)

OVHai-LLM/llama.cpp is a llama.cpp fork (MIT) that adds the olala architecture, a Mamba3 hybrid mixture-of-experts. Upstream llama.cpp cannot load these models, so they run on this separate backend. It shares the gRPC server sources with the stock llama-cpp backend, which stays unchanged.

The backend is pinned to a fork commit. Models of the Olala v1.0 mini 7A1B family are in the model gallery (olala-v1.0-mini-7a1b-*).

Notes

  • Use the bf16 file on GPU. Quantized weights on GPU backends can produce NaN. The Q5_K_M, Q6_K and q8_0-safe2 files are for CPU.
  • Do not quantize the model with a generic recipe: it can produce NaN. Use the files published by the model authors.
  • The context size is at most 32768 and is shared by parallel requests. The model cannot shift its context, so a prompt longer than the context fails.
  • The chat template takes a reasoning_effort of disabled, low, medium (default) or high. Set it per request with reasoning_effort, or per model with reasoning_effort: in the model YAML. The model card recommends temperature: 0.8, top_p: 0.9 and top_k: 40.
  • The reasoning text and tool calls come back in the usual reasoning_content and tool_calls fields.
  • This build ships for Linux x86-64 (CPU and NVIDIA CUDA 12). Other platforms are not built yet.

Setup

local-ai backends install olala
local-ai models install olala-v1.0-mini-7a1b-q5-k-m

Reference

vLLM

vLLM is a fast and easy-to-use library for LLM inference.

LocalAI has a built-in integration with vLLM, and it can be used to run models. You can check out vllm performance here.

Setup

Create a YAML file for the model you want to use with vllm.

To setup a model, you need to just specify the model name in the YAML config file:

name: vllm
backend: vllm
parameters:
    model: "facebook/opt-125m"

The backend will automatically download the required files in order to run the model.

Usage

Use the completions endpoint by specifying the vllm backend:

curl http://localhost:8080/v1/completions -H "Content-Type: application/json" -d '{   
   "model": "vllm",
   "prompt": "Hello, my name is",
   "temperature": 0.1, "top_p": 0.1
 }'

Passing arbitrary vLLM options with engine_args

A subset of AsyncEngineArgs is exposed as typed YAML fields (tensor_parallel_size, gpu_memory_utilization, quantization, max_model_len, dtype, trust_remote_code, enforce_eager, …). Anything else can be passed through the generic engine_args: map. Keys are forwarded verbatim to vLLM’s engine; unknown keys fail at load time with the closest valid name as a hint. Nested maps materialise into vLLM’s nested config dataclasses (SpeculativeConfig, KVTransferConfig, CompilationConfig, …).

Speculative decoding (DFlash, ngram, eagle, deepseek_mtp, …) is configured this way:

name: qwen3.5-4b-dflash
backend: vllm
parameters:
  model: Qwen/Qwen3.5-4B
context_size: 8192
max_model_len: 8192
trust_remote_code: true
quantization: fp8
template:
  use_tokenizer_template: true
engine_args:
  speculative_config:
    method: dflash
    model: z-lab/Qwen3.5-4B-DFlash
    num_speculative_tokens: 15

The shape of speculative_config follows vLLM’s SpeculativeConfig

  • method picks the algorithm, the remaining keys are method-specific. Drafters from z-lab are paired with specific target models; pick the one that matches your target. The drafter loads in its native precision regardless of the target’s quantization: setting.

Another example - picking a non-default attention backend (e.g. on hardware where the default cutlass kernels aren’t supported):

engine_args:
  attention_backend: TRITON_ATTN

CLI-style engine flags in options

Engine arguments can also be written in options: with vLLM’s own CLI spelling, which is handy when copying a command line out of vLLM’s documentation:

options:
  - --quantization:gptq_marlin
  - --enable-prefix-caching
  - --kv-cache-dtype:fp8_e5m2
  - --reasoning-parser:qwen3

Rules:

  • Only -- prefixed entries are treated as engine flags; everything else in options: (tool_parser:, reasoning_parser:, …) keeps its existing meaning. Both --flag:value and --flag=value are accepted.
  • Dashes become underscores (--enable-prefix-caching → enable_prefix_caching) and the value is coerced to the target field’s type. A bare --flag sets a boolean field to true.
  • Unknown or uncoercible flags are logged on the backend’s stderr and skipped rather than failing the load. engine_args: stays strict and is applied last, so it wins on conflict.

engine_args: remains the form to use for anything structured (nested configs, maps); options: is a convenience for flat flags.

Multi-node data parallelism

engine_args.data_parallel_size > 1 combined with the local-ai worker vllm follower lets a single model span multiple GPU nodes. See vLLM Multi-Node (Data-Parallel) for the head/follower configuration and a worked Kimi-K2.6 example.

SGLang

SGLang is a fast serving framework for LLMs and VLMs with a focus on prefix caching, speculative decoding, and multi-modal generation. LocalAI ships a gRPC backend that wraps SGLang’s async Engine, including its native function-call and reasoning parsers.

Setup

name: sglang
backend: sglang
parameters:
  model: "Qwen/Qwen3-4B"
template:
  use_tokenizer_template: true

The backend will pull the model from HuggingFace on first load.

Passing arbitrary SGLang options with engine_args

The same engine_args: map that the vLLM backend accepts is also honoured by the SGLang backend. Keys are validated against ServerArgs

  • SGLang’s central configuration dataclass - and forwarded verbatim to Engine(**kwargs). Unknown keys fail at load time with the closest valid name as a hint. Unlike vLLM, ServerArgs is flat: speculative decoding fields are top-level (speculative_algorithm, speculative_draft_model_path, etc.) rather than nested under a speculative_config: dict.

The typed YAML fields shared with vLLM are mapped to their SGLang equivalents (gpu_memory_utilization → mem_fraction_static, enforce_eager → disable_cuda_graph, tensor_parallel_size → tp_size, max_model_len → context_length). Anything else, including all speculative-decoding flags, goes under engine_args:.

Speculative decoding: Gemma 4 with Multi-Token Prediction

Google publishes paired “assistant” drafters for every Gemma 4 size. The drafters use Multi-Token Prediction (MTP) to propose several candidate tokens per target step, which SGLang then verifies in parallel. Flags below are transcribed verbatim from the SGLang Gemma 4 cookbook.

For consumer GPUs in the 16-24 GB range, use E4B (8 B total / 4 B effective parameters):

name: gemma-4-e4b-mtp
backend: sglang
parameters:
  model: google/gemma-4-E4B-it
context_size: 4096
template:
  use_tokenizer_template: true
options:
  - tool_parser:gemma4
  - reasoning_parser:gemma4
engine_args:
  mem_fraction_static: 0.85
  speculative_algorithm: NEXTN
  speculative_draft_model_path: google/gemma-4-E4B-it-assistant
  speculative_num_steps: 5
  speculative_num_draft_tokens: 6
  speculative_eagle_topk: 1

For smaller cards (8-12 GB), drop to E2B (5 B total / 2 B effective) by swapping the model paths to google/gemma-4-E2B-it and google/gemma-4-E2B-it-assistant; the rest of the flags stay the same.

NEXTN is normalised to EAGLE inside ServerArgs.__post_init__, so either value works - the cookbook uses NEXTN. mem_fraction_static is the share of GPU memory SGLang reserves for the model + KV pool; 0.85 is the cookbook’s default and adapts to whatever single GPU the backend is running on.

The 31 B dense and 26 B-A4B MoE Gemma 4 variants exist in the same cookbook but require --tp-size 2, so they’re not in the gallery as single-GPU recipes.

SGLang version requirement. Gemma 4 support landed in SGLang via PR #21952. The LocalAI sglang backend pins a release that includes it; if you’ve overridden the pin to an older version, this recipe will fail with a “model architecture not recognised” error at load time.

Other speculative algorithms

speculative_algorithm: also accepts EAGLE/EAGLE3 (paired with an EAGLE-style draft head), DFLASH (block-diffusion drafters from z-lab for the Qwen3 family), STANDALONE (a smaller draft LLM verifying a larger target), and NGRAM (no draft model - pure prefix-history speculation). See SGLang’s speculative-decoding docs for the full algorithm matrix.

Tool calling and reasoning parsers

SGLang’s native parsers stream tool_calls and reasoning_content inside ChatDelta - the LocalAI Python backend wires them up per-request rather than via engine_args:. Pick a parser by name:

options:
  - tool_parser:hermes
  - reasoning_parser:deepseek_r1

The full list of registered parsers lives in sglang.srt.function_call and sglang.srt.parser.reasoning_parser.

Reasoning defaults and token budgets

Set SGLang reasoning options in the model’s options: list:

options:
  - reasoning_parser:qwen3
  - thinking_budget:512
  - reasoning_default:on
engine_args:
  enable_strict_thinking: true

thinking_budget sets a positive integer token budget for reasoning on each request. Invalid, zero, and negative values produce a warning and leave the budget unset. SGLang requires engine_args.enable_strict_thinking: true to enforce the budget. LocalAI warns if you configure a budget without that engine option. Keep the budget well below the max_tokens of your requests: if max_tokens is reached first, the budget never triggers and the whole reply can be spent on reasoning, leaving the answer empty.

effort_budgets maps the request’s reasoning_effort to its own budget, so the levels differ in how long the model may think:

options:
  - thinking_budget:256                                        # fallback: no effort, or a level not listed below
  - effort_budgets:low=256;medium=1024;high=4096;xhigh=16384;max=16384

Entries are separated by ; and use the same parsing rules as thinking_budget (invalid entries are skipped with a warning). A request whose effort is not listed falls back to thinking_budget; without either, no budget is sent. A level listed here also turns reasoning on for that request, even when reasoning_default:off is set; an explicit enable_thinking: "false" in the request metadata (also sent when the model sets reasoning.disable: true) still wins. The budget is an upper bound, not a target: the model may stop thinking earlier.

reasoning_default:on or reasoning_default:off sets the default for LocalAI’s tokenizer chat template. Request metadata enable_thinking set to "true" or "false" overrides this default. An explicit prompt bypasses tokenizer template rendering. When no default or request override is set, the template keeps its own behavior.

LocalAI signals required reasoning when the rendered prompt ends with the configured parser’s opening reasoning token. An explicit output grammar disables this detection. Configure a reasoning parser that matches your model.

The backend reads these options when it loads the model. POST /models/reload rereads model configuration files but does not update options in an already loaded backend. Restarting only the backend does not reread configuration files. Restart LocalAI after changing these options to reload both the configuration and the backend.

vllm.cpp

vllm.cpp is the LocalAI team’s C++ port of vLLM: the same continuous-batching scheduler, paged KV cache and prefix caching, with no Python at inference time. It consumes either a HuggingFace safetensors model directory or a .gguf file, and applies the model’s chat template, tool-call parsing and reasoning split engine-side.

This section is the configuration reference. For installing the backend and the ready-made models the gallery ships for it, see the vllm.cpp backend page.

Setup

name: vllm-cpp
backend: vllm-cpp
parameters:
  model: "Qwen/Qwen3-4B"
context_size: 8192
template:
  use_tokenizer_template: true

Configuring the engine with engine_args

The same engine_args: map the vLLM and SGLang backends accept is honoured here, with keys spelled exactly as vLLM’s own CLI flags - so a speculative_config or kv_transfer_config block written for vLLM works verbatim. Unknown keys are ignored rather than fatal; the engine validates the documents it is handed and reports a precise error at load.

name: qwen35-a3b
backend: vllm-cpp
parameters:
  model: "Qwen/Qwen3.5-A3B"
context_size: 16384
template:
  use_tokenizer_template: true
engine_args:
  # KV cache sizing: num_blocks * block_size tokens of cache.
  block_size: 32
  num_blocks: 1024
  # Concurrency and the per-step chunked-prefill token budget.
  max_num_seqs: 32
  max_num_batched_tokens: 8192
  # Automatic prefix caching. Omit to keep the model's own default
  # (on for dense models, off for hybrid / attention-free ones).
  enable_prefix_caching: true
  # Scheduler admission order: fcfs (default), priority, or lpm
  # (cache-aware longest-prefix-match; needs prefix caching to have any effect).
  scheduling_policy: lpm
KeyMeaningDefault
block_sizeKV-cache block size, in tokens per block32
num_blocksKV-cache blocks to allocate256
max_model_lenMax sequence length; also settable as context_size / max_model_lenmodel config
max_num_seqsMax concurrent sequences the scheduler admits8
max_num_batched_tokensPer-step chunked-prefill token budgetper-arch (2048 dense, 4096/8192 MoE)
enable_prefix_cachingAutomatic prefix caching; enable_radix_attention is an accepted aliasmodel default
enable_jump_forwardJump-forward decoding, which emits grammar-forced tokens without a model step. Only affects constrained requests (grammar, JSON schema)off
scheduling_policyfcfs, priority, or lpmfcfs
tool_parser / reasoning_parserForce a parser instead of chat-template auto-detectionauto
tokenizer_configOverride the tokenizer_config.json the chat template is read from<model_dir>/tokenizer_config.json
speculative_configSpeculative decoding (see below)disabled
kv_transfer_configExternal KV connector / LMCache (see below)none
hf_overridesJSON object of config.json keys merged over the model directory’s own, as vLLM’s --hf-overrides (see the vllm.cpp backend page)none

Raising max_num_batched_tokens lets more prefill land in a single step, at the cost of decode latency for requests queued behind it. The default deliberately does not scale with max_num_seqs, which is what keeps a large concurrent prefill from blowing up the per-step activation on the hybrid architectures.

enable_prefix_caching and enable_jump_forward are tri-state at the engine boundary: omitting the key defers to a default (the model’s own capability for prefix caching, an environment variable for jump forward), while an explicit false forces the feature off. Those are genuinely different - prefix caching defaults on for dense models - so write the key only when you mean to override.

Speculative decoding

speculative_config: takes the same JSON object as vLLM’s --speculative-config. Three methods are supported.

Architecture limit. At the current engine pin, mtp and dflash are Qwen3.5 / Qwen3.6 only. The engine builds a widened speculative KV cache directly for those families rather than through the model registry, so a speculative config on any other architecture (Llama, GLM, Gemma, Mistral, …) will not work regardless of checkpoint format. ngram needs no draft weights and is not subject to this limit.

Format support. mtp and dflash now work from a .gguf target as well as safetensors. An MTP head is read from the GGUF’s nextn.* tensors when the file declares <arch>.nextn_predict_layers; a GGUF exported WITHOUT the head (converted with --no-mtp, or predating llama.cpp’s Qwen3.5 MTP support) is refused at load naming that as the reason. A DFlash draft may itself be a dflash-arch GGUF, and the target may be a GGUF too. ngram needs no draft weights and works on any format.

MTP (Multi-Token Prediction) uses a draft head shipped inside the target checkpoint’s own mtp.* tensors, so there is no second model to download. It requires a safetensors checkpoint - the mtp.* tensors do not survive GGUF conversion, and an MTP config over a .gguf model is rejected at load.

engine_args:
  speculative_config:
    method: mtp
    # Optional; defaults to the checkpoint's own head depth, which is
    # usually the right value. Must be a multiple of that depth.
    num_speculative_tokens: 1

DFlash uses a separate block-diffusion drafter that proposes a whole block of tokens in one non-autoregressive forward pass. Unlike MTP, the draft is its own checkpoint, so model: is required:

engine_args:
  speculative_config:
    method: dflash
    model: z-lab/Qwen3.6-27B-DFlash
    num_speculative_tokens: 4

The draft shares the target’s embed_tokens and lm_head, so both must come from the same model family and the target must be safetensors.

The engine does not download the draft. model: is resolved, in order, as a path as given, then as the last path segment under LocalAI’s models directory (z-lab/Qwen3.6-27B-DFlash → <models>/Qwen3.6-27B-DFlash, which is what LocalAI’s own downloader produces), then as the whole reference under the models directory. Install the draft into LocalAI first, or give an absolute path to a directory containing config.json. If none of those resolve, the load fails immediately naming every location that was tried, rather than reporting a missing checkpoint from inside the engine.

N-gram needs no draft model at all - it proposes from the prompt’s own suffix history. num_speculative_tokens is required:

engine_args:
  speculative_config:
    method: ngram
    num_speculative_tokens: 4
    prompt_lookup_min: 5
    prompt_lookup_max: 5

Auto-configuration on import. When you import a safetensors repository with backend: vllm-cpp, LocalAI reads the checkpoint’s config.json and, if it declares an MTP head (mtp_num_hidden_layers), writes speculative_config: {method: mtp} into the generated engine_args for you. An explicit speculative_config in your own config is never overwritten. Importing a DFlash draft repository is refused with a warning: a drafter cannot serve on its own, so import the target model and point speculative_config.model at the draft.

External KV cache with LMCache

kv_transfer_config: takes vLLM’s --kv-transfer-config JSON and selects an external KV-cache connector. The lm:// LMCache client lets prefill KV be stored to and reloaded from a shared lmcache.v1.server, so a prefix computed by one replica does not have to be recomputed by the next:

engine_args:
  kv_transfer_config:
    kv_connector: LMCacheConnector
    kv_role: kv_both          # required whenever kv_connector is set
    kv_connector_extra_config:
      host: 127.0.0.1
      port: 65432

kv_role is one of kv_producer (store only), kv_consumer (load only), or kv_both. An unregistered connector name, a missing role, or a malformed document fails the load with an explicit error rather than silently running without the cache.

Legacy options: list

Earlier versions configured this backend through the flat options: list, and those configs keep working. Every key in the table above is still read from there in key:value form, and engine_args wins on any key set in both:

options:
  - max_num_seqs:32
  - enable_prefix_caching:true

New configs should prefer engine_args:, which is the only place the nested speculative_config / kv_transfer_config documents can be written naturally rather than as a single-line JSON string.

Transformers

Transformers is a State-of-the-art Machine Learning library for PyTorch, TensorFlow, and JAX.

LocalAI has a built-in integration with Transformers, and it can be used to run models.

This is an extra backend - in the container images (the extra images already contains python dependencies for Transformers) is already available and there is nothing to do for the setup.

Setup

Create a YAML file for the model you want to use with transformers.

To setup a model, you need to just specify the model name in the YAML config file:

name: transformers
backend: transformers
parameters:
    model: "facebook/opt-125m"
type: AutoModelForCausalLM
quantization: bnb_4bit # One of: bnb_8bit, bnb_4bit, xpu_4bit, xpu_8bit (optional)

The backend will automatically download the required files in order to run the model.

Parameters

Type
TypeDescription
AutoModelForCausalLMAutoModelForCausalLM is a model that can be used to generate sequences. Use it for NVIDIA CUDA and Intel GPU with Intel Extensions for Pytorch acceleration
OVModelForCausalLMfor Intel CPU/GPU/NPU OpenVINO Text Generation models
OVModelForFeatureExtractionfor Intel CPU/GPU/NPU OpenVINO Embedding acceleration
N/ADefaults to AutoModel
  • OVModelForCausalLM requires OpenVINO IR Text Generation models from Hugging face
  • OVModelForFeatureExtraction works with any Safetensors Transformer Feature Extraction model from Huggingface (Embedding Model)

Please note that streaming is currently not implemented in AutoModelForCausalLM for Intel GPU. AMD GPU support is not implemented. Although AMD CPU is not officially supported by OpenVINO there are reports that it works: YMMV.

Embeddings

Use embeddings: true if the model is an embedding model

Inference device selection

Transformer backend tries to automatically select the best device for inference, anyway you can override the decision manually overriding with the main_gpu parameter.

Inference EngineApplicable Values
CUDAcuda, cuda.X where X is the GPU device like in nvidia-smi -L output
OpenVINOAny applicable value from Inference Modes like AUTO,CPU,GPU,NPU,MULTI,HETERO

Example for CUDA: main_gpu: cuda.0

Example for OpenVINO: main_gpu: AUTO:-CPU

This parameter applies to both Text Generation and Feature Extraction (i.e. Embeddings) models.

Inference Precision

Transformer backend automatically select the fastest applicable inference precision according to the device support. CUDA backend can manually enable bfloat16 if your hardware support it with the following parameter:

f16: true

Quantization
QuantizationDescription
bnb_8bit8-bit quantization
bnb_4bit4-bit quantization
xpu_8bit8-bit quantization for Intel XPUs
xpu_4bit4-bit quantization for Intel XPUs
Trust Remote Code

Some models like Microsoft Phi-3 requires external code than what is provided by the transformer library. By default it is disabled for security. It can be manually enabled with: trust_remote_code: true

Maximum Context Size

Maximum context size in bytes can be specified with the parameter: context_size. Do not use values higher than what your model support.

Usage example: context_size: 8192

Auto Prompt Template

Usually chat template is defined by the model author in the tokenizer_config.json file. To enable it use the use_tokenizer_template: true parameter in the template section.

Usage example:

template:
  use_tokenizer_template: true
Custom Stop Words

Stopwords are usually defined in tokenizer_config.json file. They can be overridden with the stopwords parameter in case of need like in llama3-Instruct model.

Usage example:

stopwords:
- "<|eot_id|>"
- "<|end_of_text|>"

Usage

Use the completions endpoint by specifying the transformers model:

curl http://localhost:8080/v1/completions -H "Content-Type: application/json" -d '{   
   "model": "transformers",
   "prompt": "Hello, my name is",
   "temperature": 0.1, "top_p": 0.1
 }'

Examples

OpenVINO

A model configuration file for openvion and starling model:

name: starling-openvino
backend: transformers
parameters:
  model: fakezeta/Starling-LM-7B-beta-openvino-int8
context_size: 8192
threads: 6
f16: true
type: OVModelForCausalLM
stopwords:
- <|end_of_turn|>
- <|endoftext|>
prompt_cache_path: "cache"
prompt_cache_all: true
template:
  chat_message: |
    {{if eq .RoleName "system"}}{{.Content}}<|end_of_turn|>{{end}}{{if eq .RoleName "assistant"}}<|end_of_turn|>GPT4 Correct Assistant: {{.Content}}<|end_of_turn|>{{end}}{{if eq .RoleName "user"}}GPT4 Correct User: {{.Content}}{{end}}

  chat: |
    {{.Input}}<|end_of_turn|>GPT4 Correct Assistant:

  completion: |
    {{.Input}}