Skip to content

AI gateway (LiteLLM)

One OpenAI-compatible endpoint for every AI client in the cluster: http://litellm.ai.svc.cluster.local:4000/v1. The admin UI and API are on envoy-internal only (LAN). Clients hold a virtual key, never a provider key. Apps: cluster/apps/ai/litellm-operator (the home-operations operator, synced first) and cluster/apps/ai/litellm (the proxy, models, teams, database, Dragonfly, route). Each model, team and key is a resource (LiteLLMModel, LiteLLMTeam, LiteLLMVirtualKey), as in bjw-s kubernetes/apps/ai. Design and plan: .archive/.plans/superpowers/specs/2026-10-26-ai-gateway-design.md.

Models

Alias Backend Cost
main ChatGPT (Codex) subscription, see below none per token
main-cheap ChatGPT (Codex) subscription, chatgpt/gpt-6.1-terra, same login as main none per token
main-lite ChatGPT (Codex) subscription, chatgpt/gpt-6-luna, same login as main none per token
or-deepseek-v4-pro OpenRouter, deepseek/deepseek-v4-pro, first fallback for main, own daily cap per token, capped
or-deepseek-v4.1-flash OpenRouter, deepseek/deepseek-v4.1-flash, fallback for every agent tier per token, capped
cheap OpenRouter, google/gemini-3.1-flash-lite, for chat and background clients per token, capped
local llama-server on nv1 (llm namespace, LFM3-1.7B, alias lfm3-1.7b), thinking off none
local-think same llama-server, thinking on, reasoning capped at 256 tokens (max_tokens 1024 is safe) none
embed CPU llama.cpp embeddings server (nomic-embed-text) none

embed is the LiteLLMModel in templates/models/embed.yaml (768-dimension vectors; Honcho depends on the dimension).

Fallbacks and budget

  • The agent tiers fail closed: they fall back to OpenRouter models only, never to local or local-think, and an exhausted chain returns the last error to the caller, so an agent pauses instead of working on the 1.7B Jetson model (it cannot see which model answered): main → or-deepseek-v4-pro → or-deepseek-v4.1-flash → error, main-cheap → or-deepseek-v4.1-flash → error, main-lite → or-deepseek-v4.1-flash → error.
  • Only cheap (Honcho, Lingarr) still falls back to local. local, local-think, embed and the or-deepseek-* aliases have no fallback.
  • LiteLLM (v1.109.1, checked in its source) chains fallbacks: a fallback hop runs with the hop's own chain, so main → or-deepseek-v4-pro would still reach local if or-deepseek-v4-pro had an entry ending there. That is why the or-deepseek-* aliases have no entry and main-lite does not go through cheap. A model already tried in the request is not tried again; at most 5 fallbacks run per request (max_fallbacks default).
  • A failed deployment is skipped for 300 s (cooldown_time) instead of being retried on every request.
  • The pay-per-token cap is routerSettings.provider_budget_config.openrouter in templates/litellmproxy.yaml: 13 USD per 30 days, about 50 zl. It is per provider on purpose: litellm_settings.max_budget is proxy-wide and would also block the free models.
  • or-deepseek-v4-pro also has its own cap, 1.12 USD per day (1 EUR at 2026-11 rates), set as max_budget and budget_duration in params.additional of templates/models/or-deepseek-v4-pro.yaml. At Hermes's call size (about 60K input tokens) it costs about 0.03 USD per call against about 0.003 USD for or-deepseek-v4.1-flash, and on 2026-11-16 it spent 2.82 USD in a few hours of ChatGPT rate limits. Once the day's cap is spent the deployment is skipped and main continues on the flash model; the 13 USD provider cap still applies to both. LiteLLM exports no remaining-budget metric for a single model, only per provider.
  • The spend counters live in a small Dragonfly (litellm-dragonfly), so a proxy restart does not reset the cap. Dragonfly itself has no persistence here; the prepaid OpenRouter balance is the hard ceiling.
  • Alerts: LiteLLMBudgetNearlyUsed (under 20% left), LiteLLMModelFailing (over half of calls to one alias failing for 15 min; requests rejected before routing, such as keyless /v1/models probes, have no model group and are ignored). It groups by model_group (the alias): a request rejected before the provider call, such as an UnsupportedParamsError, is labelled with the alias in litellm_model_name while successful calls carry the upstream model, so a per-name ratio reads 100% on the first rejection.
  • Fallback alerts, thresholds set from 2026-11-09 to 11-16, when ChatGPT 429s came in bursts of 6 to 100 an hour:
  • LiteLLMSubscriptionRateLimited: 5 or more 429s on main, main-cheap or main-lite in 30 min, for 10 min. While a deployment sits in cooldown the requests it rejects count as 429 too.
  • LiteLLMServingFallbacks: 5 or more successful fallbacks for one key and requested alias in 30 min, for 10 min. This is the only sign that an agent ran on a fallback model.
  • LiteLLMFallbackChainExhausted: any failed hop to or-deepseek-v4.1-flash, the last hop of every agent chain, in 15 min; the caller got an error. The failed-fallback counter counts every failed hop, so the filter names the last one; change it together with the chains. It has no requested_model filter: LiteLLM labels each hop with the alias that hop was asked for, so an exhausted main chain is counted as or-deepseek-v4-pro → or-deepseek-v4.1-flash, never as main → or-deepseek-v4.1-flash. A main filter kept the alert silent for the three exhaustions on 2026-11-16 at 20:24 UTC (OpenRouter key limit plus ChatGPT 429); the fixed expression fires on them when run against that data. Only agent chains reach the flash model, since cheap ends at local. A label set's first failure creates its series, which increase() reads as 0, so the rule also fires on a series whose _created timestamp is under 15 min old (the first exhaustion after a LiteLLM restart).
  • LiteLLMEmbedBackendDown: llm-embeddings has no available replica for 2 minutes. embed has no fallback, and LiteLLM retries it 8 times on InternalServerError and timeouts (model_group_retry_policy, about 64 s), which covered the 35 s rollout of 2026-11-30 with 4 backend failures and no caller error. The alert watches the backend because litellm_proxy_failed_requests_metric is never emitted here (no series in 30 days, not even for the caller-facing 500s of 2026-11-23) and litellm_deployment_failure_responses_total also counts the retries callers never see.
  • chatgpt/gpt-6.1-sol (main) does not accept reasoning_effort: none; chatgpt/gpt-6.1-terra (main-cheap) does. A client that turns thinking off that way (Hermes's smart-approval verdict) must use main-cheap, or every call is rejected with a 400 and falls back to OpenRouter.
  • Prompt caching: LiteLLM's chatgpt provider sends the Codex backend a session_id header, and the backend keeps a session's prompt cache on that key. LiteLLM takes it from the caller (x-litellm-session-id header, session_id, metadata or prompt_cache_key); without one it uses the per-request litellm_trace_id/litellm_call_id, so every call gets a new key and only a widely shared prefix stays warm (main got 13 to 21 % cache hits from Hermes, 2026-11-16, v1.109.1 llms/chatgpt/common_utils.py). A client of main, main-cheap or main-lite should send a stable x-litellm-session-id per conversation; Hermes does it through session_affinity_header. OpenRouter routes a session to one backend by itself.
  • Dashboard: Grafana folder "AI", dashboard "AI gateway (LiteLLM)" (cluster/apps/system/prometheus-stack/dashboards/litellm.json, provisioned by the ai-dashboards ConfigMap). It shows traffic, tokens, latency, failures, fallbacks, deployment state and the OpenRouter budget. Counters restart with the proxy pod, so read it with rate()/increase(); calls made with the master key show up under team None.

Teams and virtual keys

One LiteLLMTeam per client lives in templates/teams.yaml. The key itself is a LiteLLMVirtualKey (proxyRef: litellm, proxyNamespace: ai, teamID, secretName) kept next to the client app, so the operator writes the Secret into the client's namespace. No key is created by hand.

A key's models must list every alias in the team's list, fallback targets included. LiteLLM silently skips a fallback the key may not use and moves to the next one in the chain: after #6312 added the OpenRouter models to the teams but not the keys, a ChatGPT 429 on main went straight to local-think.

Team Models
hermes main, main-cheap, main-lite, or-deepseek-v4-pro, or-deepseek-v4.1-flash, cheap, local, local-think
honcho cheap, local, embed
opencode main, or-deepseek-v4-pro, or-deepseek-v4.1-flash, cheap, local, local-think
lingarr cheap, local

What each client is set to call (the team list above is what it may call):

Client Aliases in use
Hermes main (default profile, most auxiliary tasks including vision), main-cheap (worker profile, renovate-daily job), local (small background tasks); see the Hermes README
Honcho local (deriver, summary, dialectic minimal to medium), cheap (dialectic high and max, dreams), embed
opencode (Coder workspaces) main, local as the small model
Lingarr cheap

The Home Assistant voice services (whisper, piper, openwakeword) speak the Wyoming protocol, not the OpenAI API, so they run their own models outside the gateway.

opencode in the Coder workspace is installed by the template startup script from a pinned GitHub release, checked against a SHA-256 in workspace-template/main.tf (opencode_version, opencode_sha256). It is not installed with the upstream install script. After a version bump, take the new digest from the release page and change both values together; a mismatch skips the install and the workspace still starts.

main model login

main is the ChatGPT (Codex) subscription through LiteLLM's chatgpt/ provider (templates/models/main.yaml). The model is chatgpt/gpt-6.1-sol; check OpenAI's Codex models page when it is retired.

  • One account: every request uses the single login stored on the litellm-chatgpt PVC (CHATGPT_TOKEN_DIR=/app/chatgpt_tokens), whichever virtual key calls. Usage counts against that account's subscription limits.
  • No cost tracking: LiteLLM records $0 for these models, so budgets never trigger on main. Fallback happens on errors (usage limit, 429), not on spend.
  • Fallbacks: main to or-deepseek-v4-pro to or-deepseek-v4.1-flash, then an error (see Fallbacks and budget).
  • Terms: OpenAI has no explicit rule for using the Codex login in a self-hosted gateway, and its sanctioned route ("Sign in with ChatGPT") is approval-gated for hosted apps. This is a gray area; the account could be restricted. Anthropic's subscription is excluded for the opposite reason: its terms forbid it.
  • Single replica: refresh tokens are single use, so auth.json must be writable and shared; the proxy runs one replica on a ReadWriteMany CephFS volume (ceph-filesystem), so the surge pod of a rollout can start on another node.

First login (and after revoking or losing the PVC)

The proxy cannot run the device-code flow itself, so sign in once from a terminal in the pod:

  1. In ChatGPT's security settings, enable device code login for the account.
  2. Run kubectl -n ai exec -it deploy/litellm -- python -c "from litellm.llms.chatgpt.authenticator import Authenticator; Authenticator().get_access_token()".
  3. Open the printed URL, enter the code, approve.
  4. Restart the proxy by deleting the pod: kubectl -n ai delete pod -l app.kubernetes.io/name=litellm. kubectl rollout restart does nothing here, because the operator owns the pod template and drops the restart annotation. The proxy builds main only at startup; if it started before auth.json existed it skips main (log: "ChatGPT device-code login needs a human") and every request silently falls back to cheap.
  5. Check with fallbacks off, so a fallback cannot hide a failure: curl .../v1/chat/completions -d '{"model":"main","disable_fallbacks":true,...}' must answer with "model":"main". The result must still hold after another pod restart (the login lives on the PVC).

Access tokens last about ten days and are refreshed on use. To revoke: delete auth.json from the PVC, delete the proxy pod (step 4), and sign the session out in ChatGPT's security settings.

Hardening

Every workload in ai and honcho runs with runAsNonRoot, allowPrivilegeEscalation: false, a read-only root filesystem, capabilities.drop: [ALL] and seccomp RuntimeDefault, and the pods that never call the Kubernetes API have automountServiceAccountToken: false. The ai and honcho namespaces enforce Pod Security restricted; llm stays on baseline.

Workload User Writable paths
litellm 65534 /tmp (emptyDir, also HOME), /app/chatgpt_tokens (CephFS, fsGroup)
litellm-dragonfly 999 none
honcho-api, honcho-deriver 100:101 (image's own) /tmp, /app/lancedb_data (emptyDir; pgvector is the vector store, so nothing is stored there)
llm-embeddings 65534 model volume (fsGroup)

Exception: llama-server on the Jetson is not hardened. It needs the CDI/GPU device path and runs as root; the owner decided not to touch it, so llm cannot move to restricted while it runs there.

A new workload in these namespaces has to meet the same baseline or restricted admission rejects it. The Honcho and embeddings entries above show the pattern to copy.

Network policies

Cilium enforces NetworkPolicy. The gateway, its Postgres and Dragonfly, Honcho and its Postgres, the embeddings server and llama-server each have a default-deny ingress policy with explicit allows:

Target Allowed from
litellm:4000 envoy-gateway, coder, honcho, hermes-agent, lingarr (in media), the ai namespace (operator), monitoring
litellm-dragonfly:6379 litellm pods; :9999 from dragonfly-system and the replicas
litellmdb-cnpg, honchodb-cnpg the owning app (:5432), the instances themselves, cnpg, monitoring (:9187)
honcho-api:8000 hermes-agent
honcho-deriver nothing (queue worker)
llm-embeddings:8080 litellm pods in ai
llama-server:8080 litellm pods in ai; monitoring (metrics)

There is no Cilium L7 (HTTP) rule on the gateway. One was tried on 2026-12-01 and removed the same day: Cilium's ingress proxy connects to the pod from the node's router address (CiliumInternalIP) and adds no X-Forwarded-For, so LiteLLM logged every client as that address, and the per-request view it gave in Hubble duplicates LiteLLM's own metrics and spend logs per team and key. Hubble still shows which pods connect to litellm:4000.

Policies select the pods above, not the whole namespace, because the litellm-operator pod must stay reachable by the API server for its admission webhook. There is no egress policy: the gateway has to reach OpenRouter and ChatGPT. Every model call goes through the gateway: a new client gets a team, a virtual key and an entry in the litellm policy, and nothing may call llama-server or llm-embeddings directly. The llama-server policy is ingress-only and leaves the Jetson node itself untouched. Lingarr is a client too (team lingarr, alias cheap; local stays allowed on its key for a rollback); its key is entered once in the Lingarr UI (Settings, Translation, Local AI) because Lingarr stores it encrypted and ignores a plain LOCAL_AI_API_KEY.

_[VIP]: Virtual IP (Used for high-availability controlplanes) _[HA]: High Availability (often reduntant hardware/software) _[PVC]: k8s resource - Persistent Volume Claim _[PV]: k8s resource - Persistent Volume _[CNI]: k8s networking - Container Network Interface _[k8s]: Shortening of Kurbenetes _[CRD]: Custom Resource Definitions _[S3]: Simple Storage Service _[NFS]: Network File System _[DR]: Disaster Recovery