Run Multiple Local LLMs Behind One API with llama-swap: Docker, Model Routing and Auto-Unload (2026 Guide)
If you keep separate local models for coding, chat, embeddings and experiments, you eventually run into the same problem: every application needs a different endpoint, every model has its own server process, and loading a second large model can exhaust your GPU memory. llama-swap gives those servers one OpenAI-compatible front door. Your client sends a model ID; llama-swap starts the matching backend, waits for it to become healthy, forwards the request and can unload an idle model later.
This guide builds a practical local model gateway with two GGUF models, Docker, API-key protection and automatic unloading. It then explains how to keep selected models resident, allow safe concurrency, and troubleshoot slow cold starts. The examples use the official unified CUDA 13 image and the current configuration reference; adapt the image to your GPU before starting.
What llama-swap does (and what it does not)
llama-swap is a process manager and reverse proxy for local inference servers. It reads the model field from an API request and maps that ID to a configured command or upstream URL. If the requested model is not running, it starts the matching server and routes traffic to it after the configured readiness check succeeds. In a simple setup, requesting another model replaces the currently running one.
It is not a model downloader, a model converter or a guarantee that every backend supports every API feature. You still supply model files and a compatible server such as llama-server, vLLM or another OpenAI-compatible backend. The upstream server remains responsible for tokenization, inference, tool calling and model-specific behavior.
Use it when you want one stable API base URL for several local backends, on-demand loading, controlled model concurrency, or a single place to manage model IDs. If you only need one model and do not need routing, a direct Ollama or LM Studio endpoint may be simpler.
Prerequisites
- Docker Engine and the Docker CLI.
- For the example image, an NVIDIA GPU supported by the selected unified image and a working NVIDIA Container Toolkit installation. The official image matrix currently distinguishes CUDA 13 (Turing through Blackwell), CUDA 12 (Pascal through Ada) and Vulkan for AMD/other Vulkan-capable GPUs.
- Two compatible GGUF model files stored locally. The example names are
qwen-coder.ggufandgeneral-chat.gguf; use files that actually exist on your machine. - Enough system RAM and GPU memory for the model you intend to load. The router can swap processes, but it cannot make an oversized model fit into available memory.
- Basic familiarity with shell commands, YAML and HTTP requests.
On an NVIDIA host, first confirm Docker can see the GPU with the NVIDIA Container Toolkit configured. If you are on AMD, Apple Silicon, Intel graphics or CPU-only hardware, choose a matching supported backend and installation route instead of copying the CUDA command unchanged. The project also publishes a legacy CPU image; the unified image tags and their hardware targets are documented in the repository README.
1. Create a working directory and add your models
Keep configuration and model weights separate. This makes it easier to back up the small configuration file without copying tens of gigabytes of model data.
mkdir -p ~/llama-swap-lab/models
cd ~/llama-swap-lab
# Copy your own GGUF files into this directory.
# The filenames must match the paths used in config.yaml.
ls -lh models/
For this tutorial, the directory should contain:
models/
qwen-coder.gguf
general-chat.gguf
Do not assume llama-swap downloads a missing GGUF automatically. The configured command must be able to read the model file, or you must explicitly arrange a download step yourself. Check the model's license and usage restrictions before sharing it or serving it to other people.
2. Write the model configuration
Create config.yaml in the project directory. Each key under models becomes a model ID that clients send in the JSON request. The ${PORT} macro is assigned by llama-swap so each child server gets its own listening port; do not hard-code the same port for both model processes.
globalTTL: 0
healthCheckTimeout: 300
apiKeys:
- "${env.LLAMA_SWAP_KEY}"
models:
qwen-coder:
cmd: |
llama-server --port ${PORT}
--model /models/qwen-coder.gguf
--ctx-size 8192
proxy: "http://127.0.0.1:${PORT}"
ttl: 600
general-chat:
cmd: |
llama-server --port ${PORT}
--model /models/general-chat.gguf
--ctx-size 8192
proxy: "http://127.0.0.1:${PORT}"
ttl: 600
What matters in this file:
qwen-coderandgeneral-chatare stable API model IDs. They do not have to match the GGUF filenames.cmdstarts the upstream inference server. The unified image includesllama-server; if you use the standalone llama-swap binary, make sure the executable is installed and on its PATH.${PORT}avoids collisions between server processes.checkEndpointdefaults to/health; llama-swap waits for a successful health check before forwarding requests. IncreasehealthCheckTimeoutfor genuinely slow model loads, but first verify the path, command and GPU runtime.ttl: 600means unload after ten minutes of inactivity.globalTTL: 0means there is no global automatic-unload default; the per-model TTL overrides it.apiKeysrequires clients to authenticate. The key is read from the process environment rather than stored directly in the YAML file.
The example context size is illustrative, not a recommendation for every model. Adjust it to the model's supported context window and your available memory. A larger context can increase memory use substantially.
3. Start llama-swap in Docker
Generate a local API key and start the unified CUDA 13 image. The host-side port is bound to 127.0.0.1, so the service is reachable from the same machine but is not published on every network interface.
umask 077
export LLAMA_SWAP_KEY="$(openssl rand -hex 32)"
printf 'LLAMA_SWAP_KEY=%s\n' "$LLAMA_SWAP_KEY" > .env
chmod 600 .env
printf '\n.env\n' >> .gitignore
docker pull ghcr.io/mostlygeek/llama-swap:unified-cuda13
docker run --rm --name llama-swap \
--runtime nvidia \
-p 127.0.0.1:9292:8080 \
-v "$PWD/models:/models:ro" \
-v "$PWD/config.yaml:/etc/llama-swap/config/config.yaml:ro" \
-e LLAMA_SWAP_CONFIG=/etc/llama-swap/config/config.yaml \
-e LLAMA_SWAP_LISTEN=0.0.0.0:8080 \
-e LLAMA_SWAP_WATCH_CONFIG=true \
-e LLAMA_SWAP_KEY="$LLAMA_SWAP_KEY" \
ghcr.io/mostlygeek/llama-swap:unified-cuda13
Keep this terminal open while the service runs. The official unified image uses port 8080 inside the container and reads its default configuration from /etc/llama-swap/config/config.yaml. The explicit environment variables make those choices visible rather than relying on defaults.
Important: LLAMA_SWAP_LISTEN must be 0.0.0.0:8080 inside a port-published container. Binding the process to the container's own loopback address would make the host port mapping unable to reach it. The host-side 127.0.0.1:9292 binding still keeps access local to the host.
The tag unified-cuda13 is a moving image tag. For repeatable deployments, record the image digest you tested or pin a release-specific image reference available from the project's package/release listings. The project changelog listed v275 on November 20, 2026; that release changed Playground parameter defaults, not the basic model-routing configuration described here.
4. Check the API and load the first model
Open a second terminal, move into the project directory, and load the protected local environment file. Keep .env out of version control; it contains the bearer key. Then ask the gateway for its model list:
cd ~/llama-swap-lab
set -a
. ./.env
set +a
curl -sS http://127.0.0.1:9292/v1/models \
-H "Authorization: Bearer $LLAMA_SWAP_KEY"
The response should be JSON describing the configured model IDs. Now send a chat completion to the coding model:
curl -sS http://127.0.0.1:9292/v1/chat/completions \
-H "Authorization: Bearer $LLAMA_SWAP_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-coder",
"messages": [
{"role": "user", "content": "Write a Python function that reverses a string."}
],
"temperature": 0.2,
"stream": false
}'
The first request can take longer than later requests because the model process has to start and load weights. When the server is ready, the response should have the familiar chat-completion structure with a choices array. If you receive a model-load error, check the container logs and the model path before changing timeouts.
5. Switch models without changing the API base URL
Now change only the model value. The application still calls http://127.0.0.1:9292/v1/chat/completions, but llama-swap starts the second configured backend when necessary.
curl -sS http://127.0.0.1:9292/v1/chat/completions \
-H "Authorization: Bearer $LLAMA_SWAP_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "general-chat",
"messages": [
{"role": "user", "content": "Explain vector embeddings in simple terms."}
],
"stream": false
}'
With the default one-at-a-time behavior, requesting the second model swaps out the first model. This is useful when the machine cannot keep both large models in memory. It is not parallel serving: requests for different models may wait while the router changes the active backend.
6. Call the gateway from Python
Because the gateway exposes an OpenAI-compatible endpoint, you can use the OpenAI Python client and keep the same client code when changing between the configured model IDs.
python -m venv .venv
source .venv/bin/activate
pip install openai
import os
from openai import OpenAI
client = OpenAI(
base_url="http://127.0.0.1:9292/v1",
api_key=os.environ["LLAMA_SWAP_KEY"],
)
response = client.chat.completions.create(
model="qwen-coder",
messages=[
{"role": "user", "content": "Explain this Python traceback: ..."}
],
)
print(response.choices[0].message.content)
Set the environment variable in the shell that runs Python. Do not paste a production key into source code or commit it to Git. Some applications let you configure a custom OpenAI base URL; point those clients at the gateway and use the configured model ID.
7. Tune automatic unloading and cold starts
TTL is an inactivity timer, not a maximum model lifetime. Every request resets the timer. A value of 0 disables automatic unloading for that model; -1 inherits the global TTL. Use a longer value for a model that takes several minutes to load, because an aggressive TTL trades lower idle memory use for more cold starts.
For example, change the coding model to unload after twenty minutes and keep the general model resident:
models:
qwen-coder:
cmd: |
llama-server --port ${PORT}
--model /models/qwen-coder.gguf
--ctx-size 8192
proxy: "http://127.0.0.1:${PORT}"
ttl: 1200
general-chat:
cmd: |
llama-server --port ${PORT}
--model /models/general-chat.gguf
--ctx-size 8192
proxy: "http://127.0.0.1:${PORT}"
ttl: 0
After editing the file, the unified image's configuration watcher can reload it. For a manual check, use the project's UI or the documented unload API. An unload frees a process; the next request for that model can load it again. It is not a permanent disable switch.
8. Decide which models may run together
When you have enough memory for a small embedding model plus a chat model, you may want them to coexist. llama-swap has three routing engines:
- Group: easiest to reason about. Define sets of models that swap together or can coexist. A model can belong to only one group.
- Matrix: describe allowed combinations with expressions such as
(chatA | chatB) & embedder. Useful when the combinations are more complex. - Capacity: define operator-chosen resource pools and per-model requirements. The router plans around the limits you declare; it does not automatically measure your available VRAM and invent the pool sizes.
For a simple group configuration, add this only after defining the additional model IDs under models:
routing:
router:
use: group
settings:
groups:
large-models:
swap: true
exclusive: true
members: [qwen-coder, general-chat]
utility-models:
swap: false
exclusive: false
members: [embedder, reranker]
The two utility models can coexist with one another. Loading a member of the exclusive large-model group unloads other groups; the non-exclusive utility group does not itself force other groups out. Test the behavior with your actual workload and memory budget before relying on it. If you need more nuanced combinations, use the matrix router rather than stacking complicated group flags.
9. Use profiles or selectors when clients need stable names
Profiles let you switch a set of model-ID mappings together. Selectors let a virtual model ID resolve to a concrete target per request. For example, a selector using the warm strategy can prefer an already-ready target, then one already starting, and only then cold-start the first target. This can reduce avoidable model loads in a multi-backend setup, but it is not a quality-based model judge and it does not benchmark outputs.
Keep your application's model ID stable only when you have deliberately configured the corresponding profile or selector. Otherwise, use the exact IDs under models. The official profile and selector guide explains the strategies and runtime API.
10. Troubleshooting checklist
Connection refused on port 9292
- Confirm the container is running and the port mapping is
127.0.0.1:9292:8080. - Inside the container, llama-swap must listen on
0.0.0.0:8080when using Docker port publishing. - Check whether another process already occupies host port 9292.
Model does not load or times out
- Run
ls -lh models/and check that the filename and case match the path in YAML. - Check Docker logs for a missing file, invalid command, unsupported model architecture or out-of-memory error.
- Verify the container can access the GPU before increasing
healthCheckTimeout. - Make sure the health endpoint actually returns HTTP 200. A larger timeout cannot fix a wrong port or broken command.
401 Unauthorized
- Confirm the key in the client matches
LLAMA_SWAP_KEYpassed into the container. - Check that the config uses
${env.LLAMA_SWAP_KEY}exactly and that the variable is set before startup. - Send the key as
Authorization: Bearer ...or one of the documented supported authentication headers.
502 proxy error or EOF after streaming
The official troubleshooting guide documents a keep-alive edge case with some upstreams after streamed responses. If you can reproduce it with your backend, set disableKeepAlives: true for that model. Do not enable it everywhere without evidence; it changes connection reuse for each request.
Second model never runs concurrently
That is expected with the default one-model-at-a-time router. Define a group, matrix or capacity policy that permits the desired combination, and make sure the hardware has enough memory. Routing configuration cannot create additional VRAM.
Security and operational notes
- Keep the listener private by default. The example publishes only on host loopback. Do not replace that with
0.0.0.0:9292on a public server without a deliberate network and authentication design. - Enable API keys. llama-swap is unauthenticated by default. The built-in key list is a basic gate, not a full identity system: keys do not have individual roles, per-key permissions or per-key rate limits. Use a firewall and a properly configured reverse proxy or API gateway for remote access.
- Keep secrets outside YAML and Git. Environment macros fail closed when a referenced variable is missing. Rotate keys by adding a new key, moving clients, then removing the old key.
- Treat model commands as trusted code. The configuration starts local processes. Only use commands, model files and container images you trust.
- Use TLS for remote clients. Do not send bearer tokens over untrusted networks. If you put nginx in front of the service, disable proxy buffering on streaming endpoints as the project recommends.
- Review model licences and data handling. Local inference can keep prompts on your own machine, but logs, backups, monitoring, client telemetry and remote peers may still move data elsewhere.
FAQ
Does llama-swap replace Ollama or LM Studio?
Not necessarily. It is a gateway and lifecycle manager. It can route to different compatible local servers, including servers you already operate. Keep Ollama or LM Studio if they fit your workflow; add llama-swap when you need a common endpoint and explicit model swapping.
Does it download models from Hugging Face?
No automatic model download is implied by a model entry. Place the file where the configured command can read it, or deliberately add a download step to your own deployment process.
Can two models answer requests at the same time?
Yes, when the selected routing policy permits the models to coexist and your hardware can support them. The default behavior is designed around swapping rather than unlimited parallel loading.
Will every OpenAI SDK feature work?
No. The gateway supports documented API endpoints, but individual capabilities depend on the upstream server and model. Tool calling, vision, audio and context limits must be supported by the selected backend; listing a capability is not the same as enabling it in the model runtime.
How do I update llama-swap?
Check the official changelog and repository release information, choose the image or binary appropriate for your platform, and test the configuration before replacing a working deployment. For repeatability, pin a release or image digest rather than relying indefinitely on a moving tag.
Related GyanAangan guides
- Run one GGUF across multiple GPUs with llama.cpp — configure the inference server that llama-swap can launch.
- Run Ollama in Docker with an NVIDIA GPU — another local inference-server deployment path.
- Docker Model Runner with Compose Models and FastAPI — compare a different local OpenAI-compatible model-serving approach.
- Benchmark local GGUF models properly — measure your backends before choosing which model to route to.
Official references
- llama-swap source repository and README — installation methods, image variants, supported endpoints and command configuration.
- Official changelog — release history; v275 is listed as November 20, 2026.
- Configuration overview — validate and start a configuration.
- TTL and unloading — idle timers, graceful shutdown and Docker stop behavior.
- Groups, matrix and capacity routing — concurrency and model eviction policies.
- API keys and access control — authentication limitations and secret handling.
- Profiles and selectors — stable model names and runtime routing.
- Proxy and model startup timeouts — health checks, timeouts and streaming EOF troubleshooting.
- NVIDIA Container Toolkit installation guide — GPU access from Docker containers.
Final takeaway: Start with two model IDs and the default swap behavior. Confirm both work through the same API base URL, set a conservative idle TTL, and only then add concurrency rules. A small, tested configuration is easier to debug than a large routing matrix built before you know how your models behave.
