Featured project · part 3 of 3 · follows the chat UI project

🔀 Local AI: multi-user, cloud fallback, friend access

Real-world capabilities, all unlocked by editing LiteLLM's config and minting a few keys: transparent cloud fallback when local is down, per-user virtual keys you can hand to friends, editor-tool integration, and multi-engine routing (Ollama + llama.cpp side-by-side, picked from a dropdown). Mostly pure configuration evolution of what you already have.

Featured AI/ML Advanced ~30 min Prereqs: parts 1 + 2

Why this project

Parts 1 and 2 built the architecture: engine + LiteLLM + chat UI on a private Docker network, behind a Tailscale sidecar, gated by a master key. Three things you can now do without changing that architecture at all:

Every change in this project is either a yaml edit or a curl command. The compose file from parts 1 and 2 doesn't move.

👤Who this helps

  • You want to share API access with friends without inviting them to your tailnet
  • You want one URL that mixes local + cloud models behind virtual keys
  • You want usage tracking and per-user budgets
  • You want editor tools (Continue / Aider / Cursor) using your tailnet endpoint with their own credentials

🎁What you get

  • LiteLLM configured with both your local engine and cloud APIs as fallback peers
  • Per-user virtual keys with model whitelists, budgets, and rate limits
  • Transparent failover: kill local engine → friends still get answers (from cloud)
  • Editor tools using their own keys — your master key stays secret

📋Prerequisites

Mental model

The architecture diagram doesn't change from part 2. What changes is what's inside the LiteLLM box: more model entries, fallback rules, and a database of issued virtual keys.

CLIENTS PRIVATE EDGE ROUTER BACKENDS 📜 youmaster key 👋 friendsvirtual keys (NEW) 🛠️ editor toolsvirtual keys (NEW) 🔒 ts-ai sidecar (unchanged from part 1)https://ai-rig.tail-abc.ts.net 🔀 LiteLLM proxyvirtual keys · routing · fallback rules · usage trackingall NEW config in this project 🦙 Ollama (from part 1)primary path ☁️ OpenAI / Anthropic (NEW)fallback when local is down

Steps

Five steps. Add a cloud key to the env, expand LiteLLM's config to declare the fallback, restart just the LiteLLM container, mint a virtual key for a friend, verify the fallback by killing the local engine.

Add a cloud API key to the env ~3 min

Pick a cloud provider (or both — LiteLLM supports OpenAI, Anthropic, Gemini, Bedrock, Mistral, and others). For this walk-through we'll use Anthropic; substitute as you like.

Get an API key from console.anthropic.com. Add to your existing ~/local-ai/.env:

ANTHROPIC_API_KEY=sk-ant-...

Then expose it to the LiteLLM container by adding to the litellm service's environment: block in docker-compose.yml:

  litellm:
    # ... existing config ...
    environment:
      - LITELLM_MASTER_KEY=${LITELLM_MASTER_KEY?required}
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}    # NEW

Expand the LiteLLM config: alias + fallback chain ~5 min

Open ~/local-ai/litellm-config.yaml. Add a second entry with the same model_name; LiteLLM tries entries in order, falling back when one errors out. The model alias "smart" is a stable name your clients use; behind the scenes it maps to local first, cloud second.

model_list:
  - model_name: llama-3.2-3b
    litellm_params:
      model: ollama/llama3.2:3b
      api_base: http://ollama:11434

  # NEW: aliased entry, primary = local
  - model_name: smart
    litellm_params:
      model: ollama/llama3.2:3b
      api_base: http://ollama:11434

  # NEW: fallback for "smart" — cloud
  - model_name: smart
    litellm_params:
      model: claude-3-5-sonnet-20241022
      api_key: os.environ/ANTHROPIC_API_KEY

litellm_settings:
  num_retries: 2
  request_timeout: 60

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  # DATABASE_URL is read from container env (set in compose in part 2)

The Postgres sidecar from part 2 stays exactly as-is. Don't add a database_url line to this YAML — Prisma and LiteLLM both read the DATABASE_URL env var directly, and putting it in both places trips a startup bug.

Restart just the LiteLLM container ~1 min

cd ~/local-ai
docker compose up -d litellm
# Just the LiteLLM service. ts-ai, ts-chat, ollama, open-webui keep running unchanged.

docker compose logs --tail=20 litellm
# Confirm it picked up the new config (you'll see model loading messages).

Mint a virtual key for a friend ~3 min

Per-user keys with their own model whitelist, budget, and rate limit:

curl -X POST https://ai-rig.tail-abc.ts.net/key/generate \
  -H "Authorization: Bearer sk-your-master-key" \
  -H "Content-Type: application/json" \
  -d '{
    "models": ["smart"],
    "max_budget": 5,
    "duration": "30d",
    "key_alias": "alice"
  }'

# Returns: { "key": "sk-...", "expires": "...", ... }

Hand the returned sk- key to your friend. They can hit your tailnet URL with their key from anywhere on the public internet — no tailnet membership needed, since LiteLLM authenticates them via the key. Master key stays secret.

Wait — how does a friend reach the URL if they're not on the tailnet? They can't. Tailscale Serve only exposes to the tailnet. To let friends hit it from anywhere, you need Tailscale Funnel (M4L4) instead — public exposure with the auth handled at the LiteLLM layer. See the Variations section below for the swap.

Verify the cloud fallback ~3 min

Confirm fallback actually fires when the local engine is unreachable:

# Stop just the engine container — keep everything else running:
docker compose stop ollama

# Now ask LiteLLM for the "smart" model:
curl https://ai-rig.tail-abc.ts.net/v1/chat/completions \
  -H "Authorization: Bearer sk-your-master-key" \
  -H "Content-Type: application/json" \
  -d '{"model":"smart","messages":[{"role":"user","content":"hi"}]}'

# You'll get a real response — this time from Claude, not Ollama.
# Check LiteLLM's logs to see the fallback firing:
docker compose logs --tail=30 litellm | grep -i "fallback\|claude\|ollama"

# Restart the engine when you're done testing:
docker compose start ollama

Reference

✓Verify

  • A virtual-key request to /v1/chat/completions with "model": "smart" returns a response normally (from local Ollama)
  • With the engine stopped, the same request still returns a response (from cloud)
  • LiteLLM logs show which backend served each request
  • A virtual key minted with a "models" whitelist that excludes a specific model is rejected when asking for that model
  • Open WebUI from part 2 still works (its virtual key still has access to llama-3.2-3b)
  • Streaming works end-to-end. Open WebUI streams by default; from curl, add "stream": true + -N and you'll see data: {...} SSE frames ending with data: [DONE]. Serve + LiteLLM pass SSE through without buffering — no extra config.

⚠Common issues

  • Fallback doesn't fire — check num_retries in the config; check the cloud entry has working credentials. docker compose logs litellm reports per-request routing decisions.
  • Virtual keys vanish on restart — you forgot the database_url setting. Without it, LiteLLM keeps keys in memory only.
  • "Authentication Error" — wrong key, expired, or whitelisted models exclude the requested model. Try the master key first to isolate.
  • Cloud responses are slow — the first cloud call can be ~3s as TLS handshakes warm up. Subsequent calls are normal speed.

⚐Caveats

  • Cloud fallback costs money. If your local engine fails frequently, you'll be paying Anthropic/OpenAI for every request. Set max_budget on virtual keys to cap exposure; check usage regularly.
  • Local models lag frontier models on hard reasoning. Look at LiteLLM's logs to confirm which engine actually served each request.
  • The master key has full admin rights. Treat it like a database password. Rotate it periodically; never commit it to a public repo. Each friend gets a virtual key, not the master.
  • Funnel exposes your URL to the world. Even with LiteLLM auth in front, expect crawler traffic and brute-force attempts. Don't enable Funnel unless you genuinely need off-tailnet access.
  • Claude Code itself doesn't go through LiteLLM — it talks to Anthropic directly. The pattern here is for Claude-Code-adjacent tools (Continue/Aider/Cursor).

Choosing an engine for multi-user

Once you have multiple people (or multiple editor tools, or yourself + a phone + a laptop) hitting the same endpoint at the same time, your engine choice starts to matter. Ollama is the easiest to set up and has the cleanest UX, but it serializes requests by default — fine for a single user, frustrating with three. llama.cpp's server has continuous batching and handles concurrent requests gracefully on modest hardware. vLLM is purpose-built for high-throughput serving but needs a real NVIDIA GPU and more setup. The right pick depends on how many people, what hardware, and how much config you want to do.

🦙 Ollama ⚙️ llama.cpp server 🚀 vLLM
Concurrency Serialized by default. OLLAMA_NUM_PARALLEL=N env var unlocks N parallel slots — but each slot duplicates KV cache, so memory cost is N×. Continuous batching. Multiple in-flight requests share KV cache efficiently. Solid for 2–10 concurrent users on prosumer hardware. PagedAttention + continuous batching. Designed for dozens of concurrent users; the production-serving choice.
Setup effort Easiest. ollama pull and you're done. Moderate. Pick a GGUF, point the server at it, set --alias. Hardest. Python deps, GPU drivers, model loading takes minutes.
Hardware CPU + Metal/CUDA. Runs on a Mac or modest Linux box. CPU + Metal/CUDA, granular memory tuning. Same hardware footprint as Ollama. NVIDIA GPU only. Needs real VRAM (24 GB+ for useful models).
Model catalog Curated registry, simple pull. Limited to what Ollama publishes. Anything as a .gguf — unlimited via HuggingFace. HuggingFace transformers in original precision. Largest selection at full quality.
OpenAI-compat Yes (added in 2024). LiteLLM uses ollama/ prefix for richer integration. Yes, native. Use openai/ prefix in LiteLLM. Yes, native. Use openai/ prefix in LiteLLM.
Best for Single user, exploration, "just works" home setup. Multi-user prosumer setup. The right pick once you go beyond yourself. Heavy multi-user / production / dedicated GPU rig.

Practical recommendation for the path most people take through this curriculum: start with Ollama (parts 1–2 are calibrated for it, the UX is friendlier, and a single user doesn't notice the serialization). When you start sharing with friends or running editor tools alongside chat, add llama.cpp as a second engine via the multi-engine variation below — give your most-used model a llama.cpp backend (better concurrency) and keep Ollama for everything else (better UX for adding new models). LiteLLM handles the routing, so the migration is two YAML edits, not a rewrite.

Quick fix if you're staying on Ollama for now and want better concurrency without adding llama.cpp: set OLLAMA_NUM_PARALLEL=4 (or higher) on the ollama service in compose. This unlocks parallel request slots in a single Ollama instance. Memory usage scales linearly with the number of slots — measure before going wild. It's a meaningful improvement, but llama.cpp's batching is still better above ~3 concurrent users.

Variations

Public exposure

Tailscale Funnel for friends without tailnet membership

If you genuinely want friends to hit your URL from anywhere (not just your tailnet), swap the ts-ai sidecar's serve config from Serve to Funnel. Add to serve-config.json:

{
  "TCP": { "443": { "HTTPS": true } },
  "AllowFunnel": { "${TS_CERT_DOMAIN}:443": true },
  "Web": {
    "${TS_CERT_DOMAIN}:443": {
      "Handlers": { "/": { "Proxy": "http://litellm:4000" } }
    }
  }
}

Also enable Funnel in admin → Access controls (see M4L4). Now https://ai-rig.tail-abc.ts.net is reachable from the public internet — but auth still happens at LiteLLM (your master key, friend virtual keys), so unauthenticated requests are 401'd. This is the right pattern for "friends without tailnet."

Multi-engine

Ollama + llama.cpp side-by-side

Different engines have different strengths — Ollama has the smoothest UX and best model catalog, llama.cpp gives you fine-grained control over quantization and runs custom GGUFs, vLLM is the throughput champion on a serious GPU. LiteLLM is the routing layer that lets you run any combination simultaneously and surface them all as a single dropdown in Open WebUI. Pattern: one new compose service per engine, one new model_list entry per model.

Add a llamacpp service to ~/local-ai/docker-compose.yml alongside the existing ollama:

  llamacpp:
    image: ghcr.io/ggml-org/llama.cpp:server
    volumes:
      - ./models:/models           # put your .gguf files here
    command: >
      -m /models/deepseek-coder-6.7b-instruct.Q4_K_M.gguf
      --host 0.0.0.0 --port 8080
      --alias deepseek-coder       # model id llama.cpp reports on /v1/models
    networks: [ai-net]
    restart: unless-stopped
    # No host port — LiteLLM reaches it on the Docker bridge network.

Drop a GGUF into ~/local-ai/models/ first (download from huggingface.co — search for any model with "GGUF" in the name; pick a quantization that fits your RAM, e.g. Q4_K_M for ~6 GB on a 7B model). Then add the entry to litellm-config.yaml:

model_list:
  # existing Ollama entries from earlier steps...
  - model_name: llama-3.2-3b
    litellm_params:
      model: ollama/llama3.2:3b
      api_base: http://ollama:11434

  # NEW: llama.cpp speaks OpenAI-compat, route via openai/* prefix
  - model_name: deepseek-coder-6.7b
    litellm_params:
      model: openai/deepseek-coder       # match the --alias from compose
      api_base: http://llamacpp:8080/v1
      api_key: not-needed                # llama.cpp doesn't validate keys

Bring up the new service and reload LiteLLM:

docker compose up -d llamacpp litellm
docker compose logs --tail=20 llamacpp     # wait for "HTTP server is listening"

Now hit Open WebUI — the dropdown shows both llama-3.2-3b (served by Ollama) and deepseek-coder-6.7b (served by llama.cpp). Switch between them mid-conversation. From your client's perspective they're the same API; LiteLLM dispatches to the right engine per request.

Why openai/ prefix for llama.cpp? LiteLLM uses provider prefixes to pick a wire protocol. ollama/ tells it "speak Ollama's API"; openai/ tells it "speak OpenAI's chat-completions API." llama.cpp's server implements OpenAI-compat, so openai/<name> with an api_base override works. Same pattern for vLLM, LM Studio, text-generation-webui, or anything else that exposes an OpenAI-compatible endpoint.

Use case

Editor tool integration (Continue / Aider / Cursor)

All three accept custom OpenAI-compatible base URLs. Mint a virtual key dedicated to each tool (so you can rotate independently), then configure with:

  • Base URL: https://ai-rig.tail-abc.ts.net/v1
  • API key: the virtual key
  • Model: smart (or any specific model alias)

Free, private code completion that uses your home rig for the cheap stuff and falls back to a cloud frontier model when needed.

Topology

Multi-rig setup (engines on different machines)

Run a second engine on a different machine — say, a beefy GPU box for big models and a Mac mini for embeddings. Add another model_list entry with a different api_base pointing at the second rig over the tailnet (http://<other-rig>.tail-abc.ts.net:11434). Route by model name; LiteLLM dispatches transparently.

Governance

Per-user budgets and rate limits

When minting a virtual key, add "max_budget": 10 (USD), "tpm_limit": 1000 (tokens per minute), or "rpm_limit": 60 (requests per minute). LiteLLM enforces and tracks; over-budget keys get rejected.

Where this leads

You've climbed the full Local AI ladder: private API → chat UI → multi-user with cloud fallback. From here: