Setting Up LiteLLM as a Unified OpenAI-Compatible Proxy Across Local Ollama, vLLM, and Cloud Fallbacks
Running two local AI engines in your homelab feels great right up until success creates configuration sprawl. I had Ollama on port 11434 for quick model swaps, vLLM on port 8000 for parallel sweeps, and cloud keys tucked away for heavy tasks. Then I tried upgrading one quantized coder model and realized I had hardcoded host addresses, port numbers, and provider strings across nearly twenty cron scripts, container env files, and editor configs. Worse, rebooting my GPU box for a two-minute Linux kernel update crashed active multi-step agent runs mid-flight.
Instead of writing another custom wrapper script, I placed one lightweight gateway container on port 4000 in front of the entire lab. LiteLLM uses less than 256 megabytes of RAM on a standard Docker bridge and gives every CLI tool, cron patrol, and background worker a single OpenAI-compatible /v1 address. Inside one declarative config.yaml, I replaced raw host ports and provider quirks with clean intent aliases like local-code and local-general. Swapping the base URL in each tool was the whole migration for that tool.
Routine coding diffs, log summaries, and archive triage hit Ollama and vLLM first at zero marginal token cost, while OpenRouter models stand by behind the same local key as emergency backups. The first failover test looked almost effortless. After pointing all twenty-one homelab agents at port 4000, I stopped the Ollama container in the middle of an active coding prompt, and LiteLLM caught the refused socket, invoked the fallback rule, and returned a clean cloud completion without throwing an exception to the caller.
Overnight traffic revealed the real systems tax that a clean container stop never triggers. Latency-based routing backfired immediately, because a small 8-billion-parameter local model answered LAN pings in half a millisecond and the router sent complex reasoning jobs to the smallest model in the house. A saturated GPU also rarely refuses a connection; it accepts the socket and stalls while the cache drains. Explicit usage-based routing groups, 30 to 45 second timeouts, allowed_fails of 2, and a 60 second cooldown solved both: two slow timeouts trip the breaker and route prompts around the busy GPU for a full minute.
Now swapping a model across twenty-one agents takes a four-line edit in one YAML file instead of a twenty-script scavenger hunt. I can even reboot the GPU machine at noon for a kernel update while active runs glide onto fallback routes and snap back to free local silicon a minute later. The steps below build the same gateway, one config file at a time.
Prerequisites
Before creating your proxy deployment, prepare a Linux host or homelab server running Docker Engine, verify network reachability to your local Ollama and vLLM instances, maintain a Git repository (hosted on GitHub, GitLab, or self-hosted GitLab) to version-control your proxy configuration manifests, and optionally install an AI coding assistant such as Antigravity, Claude Code, or Codex for auditing YAML syntax.
- Linux homelab host running Docker Engine and Docker Compose v2.
- A functional Ollama instance running locally on port 11434 (serving models such as Qwen 2.5 Coder or Llama 3.2).
- A functional vLLM instance serving high-throughput requests on port 8000.
- Optional external cloud API keys (such as OpenRouter, Groq, or OpenAI) to serve as automatic fallback targets during local GPU saturation.
Step 1: Write the Unified LiteLLM Routing Configuration
LiteLLM uses a declarative YAML manifest to define model aliases, target endpoints, timeout thresholds, and failover chains. Create a project directory at /path/to/git/homelab-litellm/ and write a config.yaml file defining model groups that abstract away the distinction between local hardware and cloud backends:
model_list:
# Fast local coding model via Ollama
- model_name: local-code
litellm_params:
model: ollama_chat/qwen2.5-coder:7b
api_base: http://<homelab-ip>:11434
timeout: 45
max_retries: 2
# High-throughput batch inference via vLLM
- model_name: local-general
litellm_params:
model: openai/mistralai/Mistral-7B-Instruct-v0.3
api_base: http://<homelab-ip>:8000/v1
api_key: "none"
timeout: 30
max_retries: 2
# Fallback target on cloud provider for local-code
- model_name: cloud-code-fallback
litellm_params:
model: openrouter/qwen/qwen-2.5-coder-32b-instruct
api_key: os.environ/OPENROUTER_API_KEY
timeout: 20
# Fallback target on cloud provider for local-general
- model_name: cloud-general-fallback
litellm_params:
model: openrouter/meta-llama/llama-3.3-70b-instruct
api_key: os.environ/OPENROUTER_API_KEY
timeout: 20
router_settings:
routing_strategy: usage-based-routing
fallbacks:
- local-code: ["cloud-code-fallback"]
- local-general: ["cloud-general-fallback"]
allowed_fails: 2
cooldown_time: 60
general_settings:
master_key: sk-homelab-proxy-admin
store_model_in_db: false
This configuration establishes two primary model aliases: local-code and local-general. When an agent requests local-code, LiteLLM forwards the completion to Ollama on port 11434. If Ollama fails or times out after 45 seconds due to GPU contention, LiteLLM automatically redirects the prompt to OpenRouter without returning an error to the caller.
Step 2: Deploy LiteLLM Proxy in Docker Compose
Deploy the proxy service as a container with health checks and restart policies to guarantee round-the-clock availability. In your project directory, create a docker-compose.yml file alongside config.yaml:
services:
litellm:
image: ghcr.io/berriai/litellm:main-latest
container_name: litellm-proxy
restart: unless-stopped
ports:
- "4000:4000"
volumes:
- ./config.yaml:/app/config.yaml:ro
environment:
- PORT=4000
- LITELLM_CONFIG_PATH=/app/config.yaml
- OPENROUTER_API_KEY=sk-or-v1-placeholder-cloud-fallback-key
- STORE_MODEL_IN_DB=False
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:4000/health/liveliness"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
Launch the proxy container using Docker Compose:
docker compose up -d
Inspect the container startup logs to confirm that LiteLLM initialized all configured backends and mounted the configuration file without errors:
docker compose logs -f litellm
The proxy reports that it is listening on 0.0.0.0:4000 and ready to process requests across configured endpoints.
Step 3: Configure Health Probes, Cooldowns, and Failover Routing
High-concurrency agent workflows can saturate local VRAM, causing inference daemons to drop active connections or spike latency. The allowed_fails: 2 directive in config.yaml instructs LiteLLM to track consecutive connection errors. If your local Ollama or vLLM daemon fails twice consecutively, LiteLLM places that backend into a 60-second cooldown. During this window, all requests for local-code bypass the unresponsive GPU server immediately and route directly to the cloud fallback, preventing agent pipelines from hanging.
Verify proxy health and active backend reachability by querying the native endpoint:
curl -s http://<homelab-ip>:4000/health | jq .
The JSON response enumerates connected models and latency metrics, confirming your local routes are healthy.
Step 4: Route Background Agent Workloads and Verify Model Failover
With the proxy active, configure your local autonomous agents, code editors, and background scripts to point to http://<homelab-ip>:4000/v1 as their OpenAI base URL. If you have followed our earlier guides on Setting Up Ollama for Local Homelab AI Inference and Setting Up vLLM for High-Throughput OpenAI-Compatible Serving, your inference engines are already optimized for high throughput.
Test inference through the unified proxy using a standard OpenAI-compatible curl request:
curl -s http://<homelab-ip>:4000/v1/chat/completions -H "Content-Type: application/json" -H "Authorization: Bearer sk-homelab-proxy-admin" -d '{
"model": "local-code",
"messages": [
{"role": "system", "content": "You are a concise engineering assistant."},
{"role": "user", "content": "Write a one-line bash check for listening ports."}
],
"temperature": 0.2
}' | jq .choices[0].message.content
To verify automated failover behavior, simulate an outage by temporarily stopping your local Ollama container:
docker stop ollama
Re-run the exact same curl request. LiteLLM detects the connection refusal on port 11434, invokes the configured fallback rule, and returns a successful completion from OpenRouter within milliseconds. Your agent pipeline completes without interruption, and LiteLLM automatically resumes local routing once Ollama restarts.
Replicate This Build with AI
If you use an AI coding agent such as Antigravity, Claude Code, Codex, or Gemini CLI, you can paste this prompt to recreate the same functional prototype on your own gear. Replace each placeholder in angle brackets with your own values before you run it.
You are a coding agent setting up a LiteLLM proxy for my homelab in <project-dir>/litellm on <docker-host>. Show me the files before you start any containers.
My backends:
- Ollama at http://<ollama-host>:11434 serving <ollama-model-name>
- vLLM at http://<vllm-host>:8000 serving <vllm-model-name>
- An optional cloud fallback through OpenRouter using the environment variable OPENROUTER_API_KEY (never write the real key into any file you create)
Create:
1. config.yaml with a model_list that defines two intent aliases, local-code (Ollama first) and local-general (vLLM first), each with an openrouter fallback entry.
2. router_settings that use usage-based routing, a request timeout between 30 and 45 seconds, allowed_fails of 2, and a cooldown_time of 60 seconds, plus fallbacks from each local alias to its cloud entry.
3. docker-compose.yml that runs the LiteLLM proxy image on port 4000, mounts config.yaml read only, reads the master key from LITELLM_MASTER_KEY in a .env file, and restricts memory to 256 MB.
4. A .env.example listing LITELLM_MASTER_KEY and OPENROUTER_API_KEY with placeholder values, and a .gitignore that excludes .env.
Verification: start the stack, call the /v1/models endpoint with the master key and confirm both aliases appear, send one chat completion to local-code, then stop the Ollama container and send the same request again. The second request must succeed through the cloud fallback. Report each command and its output with secrets redacted.
Hardware & Gear Used in This Guide
- Homelab host server: Dedicated Linux microserver running Ubuntu 24.04 LTS and Docker Engine.
- Local inference GPU: NVIDIA GeForce RTX 3090 with 24GB VRAM running Ollama and vLLM containers.
- Proxy node host: Lightweight container consuming under 256MB RAM on the Docker bridge.
- Local network infrastructure: 2.5 GbE homelab switch providing sub-millisecond latency between agent hosts and inference nodes.
Taking It to the Next Level
- Create virtual API keys in LiteLLM for each autonomous agent so you can track token usage, enforce rate limits, and isolate budgets before one runaway loop eats them all.
- Turn on LiteLLM's logging callbacks and chart latency and fallback counts per alias, so you can see when the cooldown fires and tune allowed_fails with data instead of guesses.
- Add a response cache for repeated prompts such as nightly log summaries, which keeps identical requests off the GPU entirely.
- Point a full multi-agent development organization at the gateway, as described in Setting Up a Paperclip Multi-Agent Organization to Write and Review Code.
Do you point your AI tools straight at individual model ports, or do you run a central gateway in front of them?
Later,
SteveO
