OpenAI-Compatible Reverse Proxy
A self-hosted reverse proxy that sits in front of one or more upstream LLM
providers and exposes them behind a single, OpenAI-compatible API. Point any
OpenAI SDK or coding harness (Aider, Cline, Continue, OpenHands, etc.) at its
base_url and it works unchanged — chat, models, images, TTS, and embeddings.
Built with FastAPI + aiohttp (Python 3.11+). Streaming SSE, connection
pooling, per-key auth, per-key × model rate limiting, cost tracking, webhooks,
and an admin dashboard.
This is the public variant of the project. It ships only a small set of
example providers (Gemini + OpenAI) so you can bring your own keys. Every
credential is read from the environment — nothing is hardcoded. On top of the
chat providers you get Pollinations (free image generation) and a full
suite of TTS providers (many free, no key required).
Features
- Drop-in OpenAI surface —
/v1 endpoints for chat, models, images, TTS,
and embeddings, in OpenAI request/response shapes.
- Streaming SSE —
data: chunks terminated with [DONE], plus stream: true
and stream_options.include_usage.
- Reasoning passthrough — DeepSeek-style
reasoning_content / reasoning
fields forwarded untouched (streamed and non-streamed).
- One shared
aiohttp.ClientSession — created in the FastAPI lifespan and
reused by every provider.
- Per-key API keys — separate from upstream credentials; stored in
data/keys.json.
- Per-key × model rate limiting — sliding-window token bucket →
429.
- Usage stats & cost tracking — per key + per key × model, with monthly USD
budgets, daily request caps, key expiry, and per-model pricing overrides.
- Audit log — bounded request log (key, model, provider, latency, tokens,
cost, error).
- Webhooks — fire-and-forget notifications on
success / error / key /
other events (Discord-shaped bodies supported).
- Prometheus
/metrics — dependency-free text exposition for scraping.
- Admin dashboard + Web UI — keys, quotas, webhooks, audit, pricing,
provider priority, and an API Playground.
- CDN output — images / audio can be uploaded to your own Cloudflare R2 CDN
and returned as a public URL (
response_format=url).
Providers included
All chat/embed providers are env-driven examples — copy the pattern to add
your own.
| Provider |
Kind |
Config |
Models (examples) |
| OpenAI |
chat + embed |
OPENAI_API_KEY, OPENAI_BASE_URL |
gpt-4o, gpt-4o-mini, gpt-5-mini, text-embedding-3-small |
| Gemini |
chat |
GEMINI_API_KEYS (comma-sep, round-robin) |
gemini-3.6-flash, gemini-2.5-flash, gemini-2.5-pro |
| Pollinations |
image |
none (free) |
flux, flux-realism, flux-3, turbo |
| Edge-TTS |
tts (default) |
none (free) |
— |
| + 9 more TTS |
tts |
many free / keyless |
OpenAI FM, MurfAI, Deepgram, Qwen, Sherpa, Kitten, TTSAI, Pocket, Parler, XLNK |
Point the OpenAI provider at any OpenAI-compatible endpoint by changing
OPENAI_BASE_URL — DeepSeek, Groq, OpenRouter, or a local vLLM/Ollama server.
Adding a provider
- Drop one self-contained module into
providers/.
- Subclass the matching base class from
providers/base.py
(ChatBase / ImageBase / TTSBase / EmbedBase).
- Set
name, the upstream url, models, and read credentials from the env
(see providers/openai.py for the pattern).
- Implement the required async method(s) (
generate, generate_image,
synthesize, embed).
- Register it in
providers/__init__.py inside load_all().
No router or model-cache changes are required — registration is automatic.
Quickstart (local)
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt
cp .env.example .env
# add your provider keys to .env, e.g.
# OPENAI_API_KEY=sk-...
# GEMINI_API_KEYS=AIza...
python -m uvicorn main:app --host 0.0.0.0 --port 8000
Verify:
curl http://localhost:8000/v1/models
curl -X POST http://localhost:8000/v1/chat/completions \
-H "Authorization: Bearer demo-key" \
-H "Content-Type: application/json" \
-d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Hello"}],"stream":false}'
The default key is demo-key (create/disable keys in the admin dashboard).
Configuration
All config is read from environment variables at import time (see config.py):
| Variable |
Default |
Description |
PORT |
8000 |
HTTP port uvicorn binds to |
ADMIN_PASSWORD |
admin123 |
Password guarding /v1/admin/* |
CORS_ORIGINS |
* |
Comma-separated allowed origins |
DATA_DIR |
./data |
Where SQLite state (app.db) is persisted |
OPENAI_API_KEY |
— |
OpenAI/OpenAI-compatible key (chat + embeddings) |
OPENAI_BASE_URL |
https://api.openai.com/v1 |
Override for any OpenAI-compatible endpoint |
GEMINI_API_KEYS |
— |
One or more Gemini keys, comma-separated (round-robin) |
CDN_BASE_URL |
https://your-cdn.workers.dev |
Your R2-storage worker URL (see CDN setup) |
CDN_API_KEY |
— |
Bearer token used by your R2-storage worker |
CDN_EXPIRES |
1d |
Default file lifetime (1h,6h,12h,1d,3d,7d,30d,90d,never) |
Copy .env.example to .env and adjust as needed.
CDN setup (Cloudflare Worker + R2)
The proxy can return generated images/audio as a public URL instead of raw
bytes. When a request uses response_format="url", the proxy uploads the file
to your own Cloudflare CDN and hands back the URL. It is designed to work with
the R2-storage worker:
https://github.com/truepushkar/R2-storage
1. Create the Cloudflare R2 bucket
npx wrangler r2 bucket create your-files-bucket
2. Clone or download the R2-storage worker
R2-storage/
worker.js
wrangler.toml.example -> copy to wrangler.toml
Copy the template and point the BUCKET binding at your bucket:
[[r2_buckets]]
binding = "BUCKET"
bucket_name = "your-files-bucket"
3. Generate an API key and store it as a Worker secret
openssl rand -hex 32
npx wrangler secret put API_KEY
The worker only ever reads API_KEY from secrets/env — never commit it.
4. Deploy
Your CDN is now live at https://<your-worker>.workers.dev.
5. Point the proxy at it
In your proxy .env:
CDN_BASE_URL=https://<your-worker>.workers.dev
CDN_API_KEY=<the same 32-byte hex key you set as the Worker secret>
CDN_EXPIRES=1d
That's it. Image and speech requests with response_format="url" will now
upload to your R2 bucket and return a CDN URL like
https://<your-worker>.workers.dev/api/files/<id>.
Smoke test — hit the CDN directly to confirm auth + bucket:
curl -X PUT "https://<your-worker>.workers.dev/api/upload?filename=test.txt&expires=1d" \
-H "Authorization: Bearer <key>" \
-H "Content-Type: text/plain" \
--data-binary "hello"
The worker supports direct R2 streaming upload, multipart upload, listing,
Range requests, download/delete, a cron that purges expired files, and a
/dashboard browser UI logged-in via POST /auth/login.
Endpoints
Core (OpenAI-compatible, all under /v1)
| Method |
Path |
Description |
| GET |
/v1/models |
List all registered models |
| POST |
/v1/chat/completions |
Chat completion (stream + non-stream) |
| POST |
/v1/images/generations |
Image generation |
| POST |
/v1/audio/speech |
Text-to-speech (returns audio bytes) |
| POST |
/v1/embeddings |
Embeddings |
All endpoints require Authorization: Bearer <key>.
Admin (/v1/admin/*, guarded by ADMIN_PASSWORD)
| Method |
Path |
Description |
| GET |
/v1/admin/stats |
Usage stats |
| GET/POST/DELETE |
/v1/admin/keys |
Manage API keys |
| GET/POST |
/v1/admin/limits |
Get / set rate limits |
| GET |
/v1/admin/providers/health |
Upstream provider health + models |
| GET |
/v1/admin/models |
List all registered chat models |
| GET |
/v1/admin/costs |
Per-key quota usage + spend |
| GET |
/v1/admin/audit |
Request audit log |
| GET/POST |
/v1/admin/webhooks |
List / add webhooks |
| GET/POST |
/v1/admin/pricing |
View / set per-model USD pricing |
| GET/POST |
/v1/admin/provider-priority |
Provider fallback order |
Admin endpoints accept the password via Authorization: Bearer <admin-password>
or a ?password= query parameter.
Misc
| Method |
Path |
Description |
| GET |
/health |
Liveness probe |
| GET |
/metrics |
Prometheus text exposition |
| GET |
/ |
Dashboard Web UI |
| GET |
/admin |
Admin dashboard Web UI |
Deployment (Coolify + Docker)
The included Dockerfile (python:3.12-slim, non-root appuser) deploys
directly on Coolify or any standard Docker host.
In Coolify
- New project → Resource → Dockerfile (build from the repo's Dockerfile).
- Deploy the repository as usual.
- Persistent storage: add a volume (e.g.
proxy-data) mounted at
/app/data. This holds keys/limits/stats (app.db).
- Ports: expose port
8000 — Coolify passes PORT automatically.
- Environment variables: set
ADMIN_PASSWORD, OPENAI_API_KEY,
GEMINI_API_KEYS, and (optionally) the CDN_* values.
Local
docker build -t openai-proxy .
docker run -p 8000:8000 -v proxy-data:/app/data \
-e ADMIN_PASSWORD=change-me \
-e OPENAI_API_KEY=sk-... \
-e GEMINI_API_KEYS=AIza... \
openai-proxy
Data & Persistence
Runtime state lives in data/ (git-ignored):
data/app.db — SQLite database storing named JSON blobs:
keys.json — API keys {key: {enabled, name}}
limits.json — rate limits per key/model
stats.json — usage statistics
storage.py provides load/save (sync) and aload/asave (thread-pooled
async) helpers with WAL-mode SQLite.
Security Notes
- Change
ADMIN_PASSWORD before exposing publicly (default admin123).
- The default
demo-key is intentionally permissive — disable or remove it in
production.
CORS_ORIGINS=* allows any origin; restrict it for production.
- Never commit real credentials. Provider keys come from the environment
(
OPENAI_API_KEY, GEMINI_API_KEYS, CDN_API_KEY), and your CDN worker key
should be set with wrangler secret put API_KEY, not in wrangler.toml.
- Never add
.env or data/*.json to version control (.gitignore already
covers them).
License
Released under the MIT License.