Metadata-Version: 2.4
Name: django-ai-gateway
Version: 0.0.2
Summary: A self-hosted LLM gateway, built in Django.
Author: terminalkitten
License-Expression: BSD-3-Clause
Project-URL: Homepage, https://github.com/django-ai-sdk/django-ai-gateway
Project-URL: Repository, https://github.com/django-ai-sdk/django-ai-gateway
Project-URL: Issues, https://github.com/django-ai-sdk/django-ai-gateway/issues
Project-URL: Changelog, https://github.com/django-ai-sdk/django-ai-gateway/releases
Project-URL: django-ai-sdk, https://github.com/django-ai-sdk/django-ai-sdk
Keywords: django,llm,llm-gateway,ai-gateway,proxy,openai,anthropic,ollama
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Web Environment
Classifier: Framework :: AsyncIO
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: Intended Audience :: Developers
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: Proxy Servers
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.13
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: aiohttp>=3.14.5
Requires-Dist: cryptography>=46
Requires-Dist: django<6.2,>=5.2.6
Requires-Dist: orjson>=3.13.0
Requires-Dist: uvloop>=0.23.0
Dynamic: license-file

# Django AI Gateway

<div align="center">
  <picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/django-ai-sdk/django-ai-gateway/refs/heads/main/docs/assets/banner-dark.png"><img src="https://raw.githubusercontent.com/django-ai-sdk/django-ai-gateway/refs/heads/main/docs/assets/banner.png" alt="Django AI Gateway: a self-hosted LLM gateway, built in Django" width="100%"></picture>
  <br />
  <i>A self-hosted LLM gateway, built in Django.</i>
  <br />
  <a href="https://github.com/django-ai-sdk/django-ai-sdk">SDK</a> ·
  <a href="https://pypi.org/project/django-ai-sdk/">SDK on PyPI</a> ·
  <a href="https://github.com/django-ai-sdk/studio">Studio</a> ·
  <a href="docs/content/index.md">Docs</a>
</div>

## Project status: read this first

This is an **alpha**. Here's what that means for you:

- **Expect breaking changes.** APIs will shift as we find better patterns.
- **Migrations might be reset.** Don't rely on database schema stability between versions.
- **Not for production.** Use this for experimentation, prototypes, and side projects. Keep critical workloads elsewhere.
- **Watch the repo.** Things change quickly. Star & watch to stay in the loop.
- **Your feedback shapes the gateway.** Break things, open issues, tell us what hurts.

We'd love to have you along for the ride, just keep your seatbelt on.

## What it does

Each project gets one virtual key. Apps send every model call to one URL with that key, in the API style they already use: OpenAI, Anthropic or Ollama. The gateway:

- sends the call to the project's active provider, such as OpenAI, Anthropic, OpenRouter, a local Ollama or any API with one of those styles, with the project's own key for that provider;
- streams the reply back unchanged;
- maps model aliases, so `pony-xs` can mean a different model name on each provider;
- limits each project's open streams, requests per minute, and tokens per day and month;
- records every call's model, tokens, status and duration.

Switching a project to another provider is one choice in the dashboard. The proxy uses the new provider within a second, and the apps change nothing.

The dashboard is a set of Django pages for providers, projects, keys, limits and usage. Only active staff users can sign in, and by default they need a passkey or an authenticator app.

## Quick start

You need [uv](https://docs.astral.sh/uv/) and [just](https://just.systems/).

```sh
cp demo/.env.example demo/.env   # then fill in SECRET_KEY and GATEWAY_FERNET_KEYS
just migrate
uv run python demo/manage.py createsuperuser
just serve       # the proxy on http://localhost:8080
just dashboard   # the dashboard on http://localhost:8000, in a second terminal
```

Generate the two values with:

```sh
uv run python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
uv run python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
```

With Docker instead, after the same `demo/.env`:

```sh
docker compose -f compose.yaml up -d --build
docker compose -f compose.yaml exec dashboard python demo/manage.py createsuperuser
```

That runs the proxy on `127.0.0.1:8080` and the dashboard on `127.0.0.1:8000`, with the SQLite database in a Docker volume.

Behind portside, `just up` serves the proxy at `https://inference.gateway.test` and the dashboard at `https://admin.gateway.test`. Once, run `just certs` and add `127.0.0.1 gateway.test inference.gateway.test admin.gateway.test` to `/etc/hosts`.

Then sign in, add a passkey, add a provider and a project, and copy the project's virtual key. The [quick start](docs/content/getting-started/quickstart.md) walks through each step.

## Point your app at it

Change the base URL and the key. Nothing else.

**django-ai-sdk**, for the OpenAI generators:

```sh
OPENAI_API_URL=https://inference.gateway.test/v1
OPENAI_API_KEY=<virtual key>
```

| Generator | Settings |
| --- | --- |
| `openai_chat`, `openai_responses_chat`, `openrouter_chat`, `mistral_chat` | `*_API_URL=https://inference.gateway.test/v1`, `*_API_KEY=<virtual key>` |
| `anthropic_chat` | environment variables `ANTHROPIC_BASE_URL=https://inference.gateway.test`, `ANTHROPIC_API_KEY=<virtual key>` |
| `ollama_chat` | `OLLAMA_API_URL=https://inference.gateway.test`, environment variable `OLLAMA_API_KEY=<virtual key>` |

**OpenAI package:**

```python
from openai import OpenAI

client = OpenAI(base_url="https://inference.gateway.test/v1", api_key="<virtual key>")
```

**Anthropic package:**

```python
from anthropic import Anthropic

client = Anthropic(base_url="https://inference.gateway.test", api_key="<virtual key>")
```

**curl:**

```sh
curl https://inference.gateway.test/v1/chat/completions \
  -H "Authorization: Bearer <virtual key>" \
  -H "Content-Type: application/json" \
  -d '{"model": "pony-xs", "messages": [{"role": "user", "content": "Hello"}]}'
```

Use your own `GATEWAY_PUBLIC_URL` in place of `https://inference.gateway.test`. It is `http://localhost:8080` by default. The dashboard shows these snippets with the URL and key filled in. [Point apps at the gateway](docs/content/getting-started/connect-apps.md) lists the routes the proxy serves and the errors it returns.

## Self-hosting

The gateway is a Django app, `django_ai_gateway`. To host it, make a Django project that installs the package, as [`demo/`](demo/) does:

```sh
pip install django-ai-gateway
```

Copy `demo/settings.py`, `demo/urls.py` and `demo/asgi.py` as a starting point. They add `django_ai_gateway` to `INSTALLED_APPS` next to allauth, allauth MFA and axes (`demo/auth.py` holds the sign-in rules), set every `GATEWAY_*` setting, and include the dashboard with `include("django_ai_gateway.urls")`. The app's tables start with `gateway_`.

The project runs as two processes with the same settings and database:

- **The proxy**, the `gateway` command, is an aiohttp server for the model calls. It reads its configuration from a copy in memory, never from the database during a call. It checks for changes once a second and writes usage in the background.
- **The dashboard**, `uvicorn demo.asgi:application`, serves the gateway's own pages. There is no Django admin.

Run one proxy process. The limits are counted in its memory, and a second process would need shared counters first.

[Self-hosting](docs/content/operations/self-hosting.md) covers the Docker image, the database and a production checklist.

## The dashboard

The dashboard has these pages:

- **Overview**: calls, tokens and failed calls over 24 hours, 7 days or 30 days.
- **Projects**: each project's connected providers and their keys, the active provider, limits, virtual key and usage.
- **Providers**: endpoints and model aliases. Only superusers can change them.
- **Usage**: every call, filtered by project, provider, model and status code.
- **Passkeys and 2FA**: the signed-in user's passkeys, authenticator app and recovery codes.

What a staff user sees and changes follows Django's model permissions on the gateway models. Provider keys are write-only. Every change is written to the `gateway.audit` logger.

Users are managed on the command line: `manage.py createsuperuser`, `manage.py changepassword <user>`, or `manage.py shell` for staff users and permissions. There is no signup, password reset or password change page.

The templates use [Basecoat](https://basecoatui.com) with Tailwind 4. The built stylesheet and Basecoat's scripts are committed in `src/django_ai_gateway/static/gateway/`, so neither Docker nor the server needs Node. After you change classes in a template, rebuild the stylesheet with `just css`, which needs pnpm. CI fails when the committed stylesheet is out of date. Dark mode follows the system until the toggle sets a `theme` cookie.

## Settings

Required: `SECRET_KEY`, unless `DEBUG` is on, and `GATEWAY_FERNET_KEYS`, the Fernet keys that encrypt provider keys, newest first.

| Setting | Default | What |
| --- | --- | --- |
| `DATABASE_URL` | SQLite file | Database |
| `ALLOWED_HOSTS` | `localhost`, `127.0.0.1`, `admin.gateway.test` | Dashboard host names |
| `CSRF_TRUSTED_ORIGINS` | `https://admin.gateway.test` | Dashboard origins for form posts |
| `GATEWAY_BEHIND_TLS_PROXY` | false | Trust `X-Forwarded-Proto`. Only behind portside or another TLS proxy. |
| `GATEWAY_PUBLIC_URL` | `http://localhost:8080` | The proxy address apps call, shown in the dashboard snippets |
| `GATEWAY_REQUIRE_MFA` | true | Staff need a passkey or an authenticator app before using the dashboard |
| `GATEWAY_WEBAUTHN_RP_ID` | request host | Passkey relying party ID. Set it, for example to `admin.gateway.test`, to pin passkeys to one host. |
| `GATEWAY_WEBAUTHN_RP_NAME` | `AI Gateway` | Name the browser shows when creating a passkey |
| `GATEWAY_READ_TIMEOUT_SECONDS` | 300 | Provider silence before 504 |
| `GATEWAY_TOTAL_TIMEOUT_SECONDS` | 900 | Longest call |
| `GATEWAY_MAX_BODY_BYTES` | 16 MiB | Largest request body |
| `GATEWAY_MAX_PROVIDER_CONNECTIONS` | 1000 | Open provider connections per process |
| `GATEWAY_PLAIN_HTTP_HOSTS` | `localhost`, `127.0.0.1`, `host.docker.internal` | Hosts an endpoint may use over plain http |
| `GATEWAY_LOG_LEVEL`, `GATEWAY_CALL_LOG_LEVEL` | INFO | The gateway log, and the one-line-per-call log. WARNING on the call log saves about 5% CPU. |
| `SECURE_SSL_REDIRECT`, `SECURE_HSTS_SECONDS` | off | Set them in production |

`gateway` reads `DJANGO_SETTINGS_MODULE` like any Django tool, and also `GATEWAY_HOST`, `GATEWAY_PORT`, `GATEWAY_TLS_CERT` and `GATEWAY_TLS_KEY`.

Commands: `issue_virtual_key <project>`, `rotate_keys`, `report_usage [--project] [--since] [--by project|model|provider]`. See [Settings](docs/content/reference/settings.md) and [Commands](docs/content/reference/commands.md).

## Security

- **Virtual keys** are stored as SHA-256 hashes. The dashboard shows a new key once. A new key replaces the old one within a second.
- **Provider keys** are encrypted with Fernet. To rotate the Fernet key, put the new key first in `GATEWAY_FERNET_KEYS` for both the proxy and the dashboard and restart them, run `rotate_keys`, then remove the old key. `rotate_keys` refuses to run while any stored key cannot be decrypted.
- **The proxy** drops the app's key, cookies and forwarding headers before a call leaves, adds the provider key, and refuses compressed bodies and paths with dot segments or encoded slashes. It does not store request or reply bodies. Endpoints must use https, except for `GATEWAY_PLAIN_HTTP_HOSTS`.
- **Sign-in** is [django-allauth](https://docs.allauth.org/) with passkeys, authenticator apps and recovery codes. Five failed passwords lock that username and IP address for an hour (django-axes, `manage.py axes_reset`). Sessions end when the browser closes.
- **Passkeys** belong to one host name. Use `http://localhost:8000`, not `127.0.0.1`, for local passkeys.
- **Containers** run as a user without root rights, on a read-only file system, and publish ports on 127.0.0.1 only.

[Security](docs/content/operations/security.md) has the sign-in steps, what to do when a user loses every factor, and the full list of what the proxy forwards.

## Development

```text
src/django_ai_gateway/   the package: models, proxy, dashboard, templates, static files, commands
demo/                    the example project: settings, sign-in (allauth, MFA, axes), manage.py, Dockerfile
tests/                   pytest, with tests/settings.py
frontend/                Tailwind source for the dashboard stylesheet
docs/                    the documentation, built with dokk
```

`just` lists every recipe. The main ones:

| Recipe | What |
| --- | --- |
| `just serve [port]` | The proxy on the host, port 8080 by default |
| `just dashboard [port]` | `collectstatic`, then the dashboard on port 8000 by default |
| `just migrate` | Apply migrations |
| `just test` | pytest |
| `just check` | What CI runs: gitleaks, djLint, ruff, ty, Django checks, missing migrations, and pytest with coverage, which fails under 85% |
| `just lint` | gitleaks, then fix and format with djLint and ruff, then ty and pytest |
| `just css` | Rebuild the dashboard stylesheet, with pnpm |
| `just up`, `just down`, `just logs` | Docker behind portside |
| `just certs` | The local TLS certificate for `*.gateway.test`, with mkcert |
| `just hooks` | Install the git hooks |

`just hooks` installs [prek](https://github.com/j178/prek), which runs the hooks in `.pre-commit-config.yaml` on each commit: gitleaks on the staged changes, djLint on the templates, ruff check and format, and ty.

Plans and design notes are in [plans/index.html](plans/index.html).

## Is it any good?

[Yes.](http://news.ycombinator.com/item?id=3067434)

## License

[BSD-3-Clause](LICENSE)
