# Model Access Tier Gateway

## PURPOSE
The video's most relatable complaint is about access, not quality: the reviewer was on an
Ultra subscription and still got told "you would need an ultra subscription for it," waited
five days, and the feature never worked. That is a broken entitlement system — and it is
exactly the part of an AI product a student can build correctly. This project is a FastAPI
service that issues API keys, assigns each caller a subscription tier, decides which models
that tier may reach, proxies the allowed calls upstream with httpx, and writes every allow
and deny decision to a queryable audit table.

## WHY THIS MATTERS
Every LLM product eventually grows a gate: who may call which model, how much, and why they
were refused. Getting the refusal path right is what keeps support tickets down and SOC 2
auditors happy. This project makes entitlement an explicit, tested rule rather than a
condition buried in application code.

## HOW TO BUILD
1. `pip install -r requirements.txt` (FastAPI, SQLAlchemy, httpx).
2. Model four tables: `accounts`, `api_keys` (store a SHA-256 hash, never the raw key),
   `tiers` with a `models` allow-list, and `access_events` logging allow/deny plus reason.
3. Authenticate with a `X-API-Key` header dependency; look up the key hash, load the tier,
   and check the requested model against the allow-list.
4. On allow, forward the request upstream with httpx and time it. On deny, return 403 with
   a machine-readable reason so clients can show the upgrade path.
5. Expose `/admin/usage` returning per-key call counts and deny counts.

```python
@app.post("/v1/generate")
def generate(body: Request, account=Depends(current_account), db=Depends(get_db)):
    if body.model not in account.tier.models:
        log_event(db, account, body.model, "DENY", "tier_lacks_model")
        raise HTTPException(403, f"tier '{account.tier.name}' cannot reach {body.model}")
    ...
```

## WHEN TO USE IN PRODUCTION
Use it as the front door for multi-tenant AI products, internal platforms charging back
per team, and pilots where an expensive model must stay behind a paid tier. Do NOT use it
as a rate limiter or DDoS defence — that belongs in a gateway like Envoy. Skip the DB when
you have a single user; a config file is enough.

## HOW IT HELPS STUDENTS
They learn API-key hygiene (hashing, not storing raw secrets), SQLAlchemy relationships,
FastAPI dependency injection, upstream proxying with httpx, and audit logging — the exact
skills behind the failure the video complains about.

## STARTER CODE
`starter/main.py` is a runnable SQLite-backed service that seeds free/pro/ultra tiers and
stubs the upstream call deterministically; replace `call_upstream()` at the `# TODO`.
