A self-hosted LLM gateway with budgets, guardrails, DLP, kill switch, and cost analytics. Runs end-to-end on a single docker compose up — no cloud accounts required.
Apache 2.0, built by two co-authors as a reference implementation of an LLM gateway. The main claims below are measured in CI against a recording fake provider, and each measurement is shown the bug it exists to catch: see Proofs.
The last two badges are not typed by hand: they are CI's proofs over the last 30 days on main, rewritten after every run by .github/workflows/status.yml into the status branch.
A complete control plane for LLM traffic, split across:
packages/engine— FastAPI gateway exposing an OpenAI-compatible/v1/chat/completionsendpoint with provider routing (OpenAI, Anthropic, Gemini, and any OpenAI-compatible endpoint throughOPENAI_API_BASE), per-project budgets, response caching, DLP, kill switch, audit logs, and cost attribution. 613 offline unit tests.packages/ui— Next.js dashboard for keys, agents, budgets, privacy modes, audit logs, billing, intelligence, and playground.db/— Postgres golden schema plus a Supabase-compatibility shim so the same code runs on either a hosted Supabase project or a local self-hosted stack.docker-compose.yml— the local stack: Postgres, PostgREST, GoTrue (auth), Mailpit (local mail for magic links), nginx (URL-shape adapter), Redis, the engine with six background workers, and the UI.
git clone https://github.com/heyvaldemar/oxy-llm-gateway.git
cd oxy-llm-gateway
docker compose up -d --build --waitThe terminal recording comes from Walkthrough run 43813025035 on 2026-11-16, with the script as of 6add5aa (the magic link, the session token and the API key reach curl on its standard input): .github/workflows/walkthrough.yml ran scripts/walkthrough.sh under asciinema on a clean GitHub runner, and the script prints every command and runs it as printed. That run's cast is docs/walkthrough.cast (asciinema play docs/walkthrough.cast); the GIF was rendered from it afterwards, outside CI, with agg --speed 2 (the script hides the build output).
The first build takes a few minutes. No .env file, cloud account or provider key is needed to start. Then:
- Dashboard: http://localhost:3000
- Engine: http://localhost:8000/health
- Mail: http://localhost:8025 (Mailpit catches the sign-in links)
- Auth + REST API: http://localhost:8080 (Supabase URL shape)
Sign in at http://localhost:3000/login with any email address and open the magic link in Mailpit. During onboarding, add a provider key (OpenAI, Anthropic or Gemini), or add it later in Settings; until a provider is connected the dashboard shows demo data. Then create an API key in the dashboard and send a request:
# curl reads the key from its standard input (--config -), so it never stands on
# curl's command line, where any user of the machine could read it with ps.
oxy() { printf 'header = "Authorization: Bearer %s"\n' "$OXY_API_KEY" | curl --config - "$@"; }
oxy -X POST http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4.1-mini",
"messages": [{"role": "user", "content": "hello"}]
}'To check the whole path without a provider key, run the same end-to-end test CI runs. It signs up a throwaway user, follows a magic link through Mailpit, gets an Oxy API key and asks the gateway's healthcheck model for "pong":
bash scripts/stack_smoke.shTo go further by hand, the workshop is a lab of about 80 minutes that starts from this quickstart and has you meet each control: a request the budget cannot cover, a secret stopped by DLP, a killed agent session, a revoked key, and the audit row each one leaves.
The codespace (4 cores, 16 GB) builds and starts the whole stack with the recording fake provider from proofs/ in place of a model provider, so no key is needed and no request leaves the codespace. The stack runs on secrets generated for the codespace on its first start, not on the published development defaults, and on every start .devcontainer/start.sh makes a fresh demo organization, project, API key and agent session and puts them in the terminal's environment; none of it is stored in the repository. The dashboard opens on port 3080: sign in as $OXY_DEMO_EMAIL, and the link arrives in Mailpit on port 8025.
In a terminal:
# curl reads the key from its standard input (--config -), so it never stands on
# curl's command line, where any user of the machine could read it with ps.
oxy() { printf 'header = "Authorization: Bearer %s"\n' "$OXY_API_KEY" | curl --config - "$@"; }
# 1. A request through the gateway; the fake provider answers
oxy -s -w '\nHTTP %{http_code}\n' localhost:8000/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"hello"}]}'
# 2. The same request carrying a GitHub token, made up on the spot: DLP refuses it (451)
oxy -s -w '\nHTTP %{http_code}\n' localhost:8000/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"deploy with ghp_'"$(openssl rand -hex 18)"'"}]}'
# 3. Kill the demo agent session, then send one more request in it (410)
oxy -s -w '\nHTTP %{http_code}\n' -X POST localhost:8000/v1/agent-sessions/$OXY_SESSION_ID/kill
oxy -s -w '\nHTTP %{http_code}\n' localhost:8000/v1/chat/completions \
-H 'Content-Type: application/json' \
-H "X-Oxy-Agent-Id: $OXY_AGENT_ID" -H "X-Oxy-Session-Id: $OXY_SESSION_ID" \
-d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"next step"}]}'A demonstration, not a measurement: CI builds this devcontainer and runs these requests as printed, plus the smoke test (job Codespace devcontainer, smoke and the README's requests), and the measured claims are the Proofs. The session stays killed: a second run of the third request answers 404 for the kill and 410 again.
┌──────────┐ ┌─────────────────┐
Browser │ UI │────────── HTTP :3000 ───────────│ Next.js 16 │
│ (Next.js)│ │ + Turbopack │
└────┬─────┘ └────────┬────────┘
│ │ SSR
│ ┌─────────────────────┘
│ /auth/v1 + /rest/v1
▼
┌──────────────────────────────────────────────────┐
│ nginx-postgrest :8080 (path-shape adapter) │
│ /auth/v1/* → gotrue:9999 │
│ /rest/v1/* → postgrest:3000 │
└─────────┬─────────────────────────┬───────────────┘
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│ GoTrue │ │ PostgREST│
│ (auth) │ │ (REST) │
└─────┬────┘ └─────┬────┘
│ │
└────────────┬────────────┘
▼
┌─────────────────┐
│ Postgres 16 │
│ schema + RLS │
└─────────────────┘
┌─────────────────┐ ┌─────────────────┐
API │ Engine :8000 │◄────────│ Redis 7 │
│ (FastAPI) │ │ cache + state │
└────────┬────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ OpenAI /Anthropic
│ /Gemini /Ollama │ outbound LLM calls
│ /vLLM │
└─────────────────┘
The same gateway code path runs against a hosted Supabase project (set SUPABASE_URL to your project) or against the bundled local stack (the default). PostgREST + GoTrue replace the equivalent Supabase Cloud services, sharing one JWT secret so tokens flow through to row-level security unchanged.
What the gateway does today (heuristic where noted, best-effort, no SLA); what is not wired yet is listed under Scope and honest limitations:
- Budgets — a spend cap per project, reserved atomically before a request reaches a provider and settled at the real cost after it; alerts at 80, 95 and 100%: by email through SendGrid when
EMAIL_ENABLEDandSENDGRID_API_KEYare set, and to the organization's Slack, Discord and Zapier webhooks enabled in its notification settings (tested against a recorded webhook, not a live workspace). Agents have budget fields in the schema, but the request path enforces the project's cap only - Kill switch — best-effort stop on agent sessions, blocks further requests
- Loop detection — heuristic detection of repeated/stuck agent calls
- Response caching — deterministic requests (
temperature0) cached in Redis per organization for 7 days; a hit is still recorded and charged to the budget - Cost optimizer — heuristic recommendations (model switch, caching, throttling) based on recent request logs
- Request export — the organization's request log as CSV (
GET /v1/exports/requests.csv) - Privacy modes —
zero_prompt_logging,metadata_only,debug_full - DLP — regex detection before a request leaves the gateway: API keys and tokens (OpenAI, Anthropic, AWS, Stripe live, GitHub, Slack, Google), JWTs, private keys and card numbers. Email addresses alone are not blocked.
- Audit logs — a
request_logsrow for every request made with a valid key, refusals included (by the budget, DLP, the kill switch, the burst limit, a suspended organization, a body that is not JSON), kept when the key is revoked; and an admin audit log; a retention window per organization is stored (/v1/privacy) - Rate limiting and security headers — per-key throttling, HSTS/CSP/etc.
- Geo / IP protections — header-first country/region blocking
- Notification settings — Slack, Discord and Zapier webhook URLs and events per organization are stored (
/v1/notifications/settings); budget alerts are sent to them, see below for the rest - Self-hosted models — a model named
vllm/<name>,ollama/<name>orlocal/<name>goes to your own server, with no provider key:VLLM_BASE_URL,OLLAMA_BASE_URLorLOCAL_HTTP_BASE_URLsay where (a server started with its own key gets it asVLLM_API_KEYand the like, or on the provider page). A local model bills nothing per token unless you setLOCAL_PROMPT_PRICE_PER_MILLIONandLOCAL_COMPLETION_PRICE_PER_MILLIONto what a million tokens cost you, and then a project's budget caps it like a hosted one. DLP, the kill switch, budgets and the audit trail run on it as on any other model, and the local proof measures that against the recording fake. Any other OpenAI-compatible endpoint, an inference gateway included, still goes throughOPENAI_API_BASE. - Intelligence + security score — heuristic dashboard signals (advisory only)
For the canonical mapping between feature, code, tests, and docs see docs/product/FEATURE_MATRIX.yml.
Three public repositories, three places to stop an AI request before it does damage:
| Repository | Where it stands | What it enforces |
|---|---|---|
| kubernetes-air-gapped-ai-agent | inside a cluster with no route to the internet | the boundary at the tool server: the agent reaches tools only through MCP, models arrive as signed weights checked at admission |
| kubernetes-llm-inference-gateway | in front of self-hosted model replicas | routing by queue and cache across vLLM replicas behind the Gateway API Inference Extension, cost per token measured |
| Oxy (this repository) | in front of model providers, hosted or self-hosted | a budget per project, DLP, a kill switch for agent sessions, an audit row for every authenticated request |
Oxy speaks the OpenAI API on both sides, so an inference gateway like the second one can sit behind it as one more OpenAI-compatible provider. The three have not been run together yet.
proofs/run_proofs.py starts from a running stack whose engine sends every OpenAI-model request to a fake provider that records what it receives (proofs/docker-compose.proofs.yml). Each proof signs up its own users; secrets are generated at random on every run.
| Claim | Measured |
|---|---|
| A budget is never overspent | 541 requests, 100 at a time, against a $0.05 budget: the provider served 35 completions, exactly what the budget buys; overspend $0. After the budget worker's sync cycles, 0 of 20 more were served, and 0 of 20 after Redis lost the spend counter |
| DLP stops secrets before the provider | 11 secret types sent; 0 reached the provider; a clean control request did. A 400,018-character prompt built for the patterns' worst case was answered in 0.14 s; with either 1.1.0 pattern planted back, no answer within 60 s |
| The kill switch stops a session | 214 requests started after POST /v1/agent-sessions/{id}/kill returned; 0 reached the provider; first blocked response 77 ms after the call. Another tenant's kill attempt answered 404. The killed session's row records who, when and why |
| A local model gets the same gateway | 12 requests for vllm/proof-model against a $0.02 budget, at a price of $0.0055 a request that the operator sets: the server served 3, exactly what the budget buys; overspend $0, 9 answered 402. 11 secret types sent to it: 11 refused with 451, 0 reached the server, a clean control request did. A killed session's next 5 requests answered 410; 0 reached the server. No provider key is configured anywhere |
| Each organization's requests leave with its own provider key | 80 Gemini requests alternating between two organizations, each with a Google key of its own in the vault, 40 in flight at a time: the recording fake saw 80 with the sender's own key, 0 with the other organization's and 0 with any other. With the key made a setting of the whole process again, as 1.1.1 had it, 21 of the 80 crossed |
| An MCP server is reached only where the operator allows | 4 addresses inside the stack (the fake provider under its own name, 127.0.0.1, the metadata address 169.254.169.254, Redis) refused with 400 at registration; a URL stored before the check refused when its tool was called (502); 0 requests reached inside. The server named in MCP_ALLOWED_HOSTS was registered and called (200) |
| One tenant cannot act as another's agent | 25 requests carrying another tenant's agent and session ids: 25 refused with 403, 0 reached the provider, 0 logged against that tenant's agent |
| A revoked key stops at once | a key used a moment before (so cached) is revoked: 10 of 10 next requests refused with 401, 0 reached the provider |
| Without Redis, nothing unchecked gets through | Redis paused for 8.3 s: 4 requests against a budget answered 503, 4 in a killed session 410 (decided by Postgres); 0 of the 8 reached the provider. 2 requests needing neither check were served |
| The browser cannot reach the engine's data | 27 database functions called through PostgREST with the public anon key and with a user's token: 0 callable; 41 tables, all with row-level security; 0 policies open to the browser roles |
| No key is stored in the clear | 16 tenants' keys checked against every name and value of 79 Redis keys: 0 found. One provider secret stored twice in the bundled vault: 2 different ciphertexts; one changed byte: refused |
| Every request is audited | 1,011 requests sent with a valid key by the proofs above, 1,011 request_logs rows, refusals included, 5 of them refused by the burst limit (429). A key revoked in the dashboard kept all 4 of its rows; request_logs.api_key_id is ON DELETE SET NULL |
proofs/plant_violations.py then plants, one at a time, the bug each proof exists for (a non-atomic reservation, the old spend ledger that reset every minute, DLP switched off, the email and JWT patterns made quadratic again, the kill state ignored, another tenant's ids accepted, a revoked key left in the cache, fail-open checks when Redis is down, the database functions and an open policy re-granted to the browser roles, the cache named by the raw key, audit writes dropped, a dashboard revoke that deletes the key and cascades its audit rows, a burst-limited request left without its row, a killed session's row that forgets who killed it and why, a local model that needs a provider key again, a local model's price ignored, the Gemini adapter's key a setting of the whole process again (two organizations' requests cross), every address counted as public for an MCP server, a tool call that trusts the stored URL, the vault's old AES-CBC with one all-zero IV), requires that proof to fail, and restores the code. CI runs both on every push and daily (job Proofs, each shown its planted violation) and keeps the JSON; the branch status keeps the last 30 days.
docker compose -f docker-compose.yml -f proofs/docker-compose.proofs.yml up -d --build --wait
python3 proofs/run_proofs.py
python3 proofs/plant_violations.pyEvery number in this table comes from one run: CI run 46947270442 (job Proofs, each shown its planted violation) on 2026-12-02, on pull request #52 at 087a7e7, the code of 1.1.2 (the release adds only this table's text), where all twelve proofs held and all twenty-one planted violations were caught. The stack is the default one, a single engine process on a GitHub-hosted runner. The latest run's numbers, with its run id, are in status.json; they move a little from run to run (the kill switch's first refusal, the number of requests sent).
- No SLAs. Uptime, latency, retention, savings, and security are all best-effort.
- Intelligence, optimizer, forecasts, and scores are heuristic. Treat them as advisory, not billing truth or compliance certification.
- The vault shim uses pgcrypto's OpenPGP symmetric encryption with a configurable key (AES-256, a fresh salt and IV per secret, a changed ciphertext fails to decrypt). It is not an AEAD construction and is weaker than Supabase's pgsodium-backed Vault. Review
db/supabase-compat.sqlbefore storing real provider keys in it. - Email auto-confirm is on by default so signups work without SMTP. Disable
GOTRUE_MAILER_AUTOCONFIRMand configure SMTP for any deployment that handles real users. - A budget is the project's total spend, not a monthly allowance: nothing resets it. The Redis counter is the ledger; the budget worker copies it to
projects.current_spendevery 60 s, and if Redis loses the counter it resumes from that copy, so at most the last minute's spend can be spent again. - Not wired in this release. These have code or schema in the repository but do not work end to end, and the dashboard does not offer them: accepting team invitations (
/management/team/invite/acceptanswers 501; an operator adds members inorganization_members); SSO sign-in (/auth/sso/callbackanswers 501, three database functions are missing); exporting a user's data (/management/export-dataanswers 501, its database function is missing); delivery to registered webhooks, and Slack, Discord and Zapier alerts other than the budget's; cost-spike auto-suspend (the worker reads a column that does not exist); scheduled deletion by the retention window; approving an MCP tool call; redeeming referral credits; cost attribution tags (nothing writes them); key-rotation headers; enforcing agent budgets, team-member caps and per-tool MCP limits. - Without Redis the gateway refuses what it cannot check. A request against a budget answers 503; a request in an agent session is decided by the session's row in Postgres, or refused. Other requests are still served, a little slower (the API key is looked up in Postgres).
- Backend: Python 3.12, FastAPI, asyncpg-style PostgREST client (custom over httpx), structlog, Redis with Lua scripts for atomic budget operations
- Frontend: Next.js 16 (App Router, Turbopack), TypeScript strict, supabase-js +
@supabase/ssr, Radix UI primitives, Tailwind - Data: Postgres 16, PostgREST 12, GoTrue (Supabase Auth) v2
- Infra: docker-compose, nginx (path adapter), Caddy for TLS
- Tests: pytest (613 offline tests), Playwright + Vitest on the UI
oxy/
├── packages/
│ ├── engine/ # FastAPI gateway (routes/, core/, middleware/, providers/, workers/)
│ └── ui/ # Next.js dashboard (src/app/, src/components/, src/lib/)
├── db/
│ ├── schema.sql # Golden schema (3000+ lines)
│ └── supabase-compat.sql # Auth/vault/role shim for self-hosted Postgres
├── nginx/postgrest.conf # URL-shape adapter for local stack
├── docker-compose.yml # Local stack (14 containers)
├── docker-compose.prod.yml # Deployment with TLS via Caddy
├── docs/ # Operator documentation
├── scripts/ # Dev menu, test runners, schema initializer
├── DEPLOY.md # Hosted-Supabase deployment guide
├── SECURITY.md # Cryptography, RLS, audit, incident response
└── DEV_NOTES.md # Daily development workflows
make test-core # 613 offline unit tests, about ten seconds
make test-integration # requires a running engine + live external servicesUI:
cd packages/ui
pnpm test # vitest
pnpm test:e2e # playwrightThe dev stack ships local defaults in docker-compose.yml; packages/engine/.env and packages/ui/.env.local are optional overrides. Read SECURITY.md before exposing it. For a deployment others can reach, see packages/engine/ENV.example and DEPLOY.md. Key environment variables:
| Variable | Purpose |
|---|---|
SUPABASE_URL |
Point engine at hosted Supabase or local nginx (default http://nginx-postgrest:8080) |
SUPABASE_SERVICE_KEY |
Service-role JWT signed with SUPABASE_JWT_SECRET |
SUPABASE_JWT_SECRET |
Shared between GoTrue, PostgREST, and JWTs (default is dev-only) |
SUPABASE_VAULT_KEY |
key for vault.create_secret (pgp_sym_encrypt) in the compat shim |
REDIS_URL / REDIS_PASSWORD |
Cache and atomic state |
AUTHENTICATOR_PASSWORD |
PostgREST's database password. Unset, the database's first boot generates one (db/03-authenticator-password.sh) |
OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY |
Optional org-wide provider keys (or configure them per organization in the UI) |
GEMINI_API_BASE |
Optional. Another server that speaks Gemini's API, as OPENAI_API_BASE does for OpenAI-compatible endpoints (default Google's) |
ALLOWED_ORIGINS |
Browser origins allowed to call the engine (default http://localhost:3000) |
NEXT_PUBLIC_SITE_URL |
Public URL of the UI, used for sign-in redirects and metadata |
STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET |
Optional. Without them the Stripe endpoints answer 503 and everything else works |
Dependabot proposes patch and minor updates once a week, once a release is seven days old, one grouped pull request per ecosystem: GitHub Actions, the engine's Python packages, the UI's npm packages and the Dockerfiles' base images. dependabot-automerge.yml merges such a pull request once CI, with the proofs and the devcontainer, and CodeQL pass for its commit, and only when every dependency it moves is stated as a patch or minor update. The images pinned by digest in the compose files are checked each week by freshness.yml, the fleet's freshness check. They are not refreshed automatically: a pin that fell behind fails that workflow, the fleet's heartbeat reports the red run (it watches every public repository's workflows, including a schedule GitHub switches off after 60 quiet days), and the bump is made by hand in a pull request that passes the same checks as any other.
Major versions are not proposed: each is a migration, made by hand in its own pull request. A known vulnerability is not left to them: CI runs pip-audit on the engine's requirements and pnpm audit on the UI's production dependencies (high and critical) on every push and pull request and every day, and fails when it finds one, whether its fix is a major version or not. Held back on 2026-11-15, to be reviewed on 2027-02-15:
- base images: Python 3.12 (3.15 is out) and Node 22 LTS (26 is out);
- engine:
anthropic2,redis8,stripe17,structlog26 (andredisstays on 5.2: with 5.3, concurrent commands queue behind each timeout while Redis does not answer, and the fail-closed proof timed out), and for developmentpytest9,pytest-asyncio1,pytest-cov7,black26,isort9,mypy2; - UI: TypeScript 7, ESLint 10, Vite 8 with
@vitejs/plugin-react6, Vitest 5, jsdom 31,@sentry/nextjs11,framer-motion14,lucide-react1,sonner2,@testing-library/jest-dom7,@types/node26.
pnpm-workspace.yaml lifts three build-time packages past their advisories until the packages that pull them in ship the fixes: glob 14 and minimatch 11 under @sentry/nextjs 10 (its bundler plugins) and typescript-eslint, and webpack 5.104.1 or later, the peer of Sentry's webpack plugin. None of them reaches the running services.
Apache License 2.0: LICENSE holds the license text unchanged, NOTICE the copyright.
Oxy has two co-authors and maintainers, with an equal share in it. Both of us shaped every part of it, from the first idea to the architecture, and each of us brought a different side of the same decade in DevOps.
- Tatiana Mikhaleva (DevOpsPink, devops.pink), Docker Captain: the developer experience. How a team gets from
git cloneto its first working key with onedocker compose up, the dashboard where a project owner sees spend, keys and every refusal, and the documentation that makes the gateway's rules obvious before they bite. - Vladimir Mikhalev (heyvaldemar, heyvaldemar.com): the security model. What Oxy refuses and why, behind the budgets, DLP, the kill switch and the audit trail, and the proofs in CI that show each control holding, each one shown the bug it exists to catch.
See MAINTAINERS.md.
A reference implementation, not a managed service: there is no SLA, and the heuristic features (optimizer, intelligence, scores) are advisory. Issues and pull requests are welcome.
