Build Your Own LLM API: An Open-Weight Model Behind a Gateway You Control

A terminal showing a curl request to a self-hosted chat completions endpoint and a streamed reply, next to the title Build your own LLM API

Every few months someone on a team I work with asks the same question: "Can we just run our own model?" Usually it comes after a privacy review, a surprising invoice, or a provider changing a model under them without warning. The honest answer is yes, and the model is the easy part. What takes thought is everything around it: who is allowed to call it, how much they can use, what happens when ten people hit it at once, and how your existing code talks to it without a rewrite.

This post is the setup I keep coming back to. It is small enough to run on one GPU box and boring enough to leave running.

What we are building

Two containers on a private Docker network:

  1. A model server. I use vLLM. It loads an open-weight model, batches concurrent requests on the GPU, and already exposes OpenAI-compatible endpoints such as /v1/chat/completions.
  2. A gateway. A few hundred lines of FastAPI that sits in front of vLLM and is the only thing exposed to the outside. It checks API keys, rate limits each key, caps how many tokens a request may generate, passes streaming responses straight through, and records usage.
Diagram: client apps call a FastAPI gateway over HTTPS; the gateway checks keys, rate limits and caps tokens, then forwards to a vLLM model server on an internal port backed by a GPU
The gateway is the only published port. vLLM never sees the internet.

Why not expose vLLM directly? vLLM can check a single static API key, but that is all. One shared key means you cannot revoke one client, cannot tell who burned the GPU at 3 a.m., and cannot stop a buggy agent loop from requesting 32,000 tokens a hundred times a minute. Those are the problems the gateway exists to solve.

Because both layers speak the OpenAI protocol, every client you already have keeps working. You change a base URL and an API key, nothing else.

Picking a model and a GPU

For a first deployment I would start with a 7–8B instruction-tuned model such as Qwen2.5-7B-Instruct or Llama 3.1 8B Instruct. In 16-bit precision the weights take roughly 15–16 GB, so a 24 GB card (an RTX 4090, an L4 or an A10G) leaves several gigabytes for the KV cache, which is what lets vLLM serve many conversations at once.

Two settings matter most on a card that size:

  • --max-model-len sets the longest context you will accept. Every extra token of context is KV cache that cannot be used for another user. I start at 8,192 and raise it only if a real use case needs more.
  • --gpu-memory-utilization is the share of VRAM vLLM may claim. 0.90 is a sensible default on a dedicated box.

If the model does not fit, use a quantized checkpoint (AWQ or GPTQ) before buying a bigger GPU. For chat and extraction work the quality drop is usually smaller than people expect.

Step 1: run vLLM on its own

Before writing any gateway code, make sure the model server works alone:

docker run --rm --gpus all --ipc=host -p 8000:8000 \
  -v hf-cache:/root/.cache/huggingface \
  vllm/vllm-openai:v0.9.1 \
  --model Qwen/Qwen2.5-7B-Instruct \
  --served-model-name local-chat \
  --max-model-len 8192 \
  --gpu-memory-utilization 0.90

The first start downloads the weights into the hf-cache volume, so later restarts are quick. When the log says the server is listening, send it a request:

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "local-chat", "messages": [{"role": "user", "content": "Say hi in five words."}]}'

--served-model-name is a small thing I always set. Clients ask for local-chat instead of a long Hugging Face path, so swapping the underlying model later does not break anyone's config.

Step 2: the gateway

The gateway does five things, in this order, for each request: authenticate, rate limit, clamp the request, forward it, and record what it cost.

API keys

I generate keys myself and store only their SHA-256 hashes, so a leaked config file does not leak working keys:

python -c "import secrets; print('sk-local-' + secrets.token_urlsafe(32))"
# give the printed key to the client, then store only its hash:
python -c "import hashlib, sys; print(hashlib.sha256(sys.argv[1].encode()).hexdigest())" sk-local-...

The hashes go into a plain text file, one per line, with an optional label after a space so the logs say mobile-app instead of a hash prefix.

The code

# gateway/app.py
import hashlib
import json
import logging
import os
import time

import httpx
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import JSONResponse, StreamingResponse

UPSTREAM_URL = os.environ.get("UPSTREAM_URL", "http://vllm:8000")
MODEL_NAME = os.environ.get("MODEL_NAME", "local-chat")
MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "1024"))
RATE_PER_MINUTE = float(os.environ.get("RATE_PER_MINUTE", "30"))
KEYS_FILE = os.environ.get("KEYS_FILE", "/run/secrets/api_keys")

log = logging.getLogger("gateway")
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")


def load_keys(path):
    """Map sha256(key) -> label. Each line: '<hash> [label]'."""
    keys = {}
    with open(path) as fh:
        for line in fh:
            parts = line.split()
            if parts:
                keys[parts[0]] = parts[1] if len(parts) > 1 else parts[0][:12]
    return keys


KEYS = load_keys(KEYS_FILE)
app = FastAPI()
client = httpx.AsyncClient(base_url=UPSTREAM_URL, timeout=httpx.Timeout(300, connect=5))


class TokenBucket:
    """Allows short bursts but holds each key to RATE_PER_MINUTE on average."""

    def __init__(self, per_minute, burst):
        self.rate = per_minute / 60.0
        self.capacity = burst
        self.tokens = burst
        self.updated = time.monotonic()

    def take(self):
        now = time.monotonic()
        self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
        self.updated = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False


buckets = {}


def authenticate(authorization):
    if not authorization or not authorization.startswith("Bearer "):
        raise HTTPException(401, "missing API key")
    digest = hashlib.sha256(authorization.removeprefix("Bearer ").encode()).hexdigest()
    label = KEYS.get(digest)
    if label is None:
        raise HTTPException(401, "invalid API key")
    return label


def log_usage(label, usage, started):
    if usage:
        log.info(
            "key=%s prompt=%s completion=%s seconds=%.2f",
            label, usage.get("prompt_tokens"), usage.get("completion_tokens"), time.monotonic() - started,
        )


@app.get("/healthz")
async def healthz():
    try:
        r = await client.get("/health", timeout=5)
        return {"ok": r.status_code == 200}
    except httpx.HTTPError:
        return JSONResponse({"ok": False}, status_code=503)


@app.post("/v1/chat/completions")
async def chat_completions(request: Request, authorization: str | None = Header(None)):
    label = authenticate(authorization)
    bucket = buckets.setdefault(label, TokenBucket(RATE_PER_MINUTE, burst=5))
    if not bucket.take():
        raise HTTPException(429, "rate limit exceeded", headers={"Retry-After": "2"})

    body = await request.json()
    body["model"] = MODEL_NAME
    body["max_tokens"] = min(int(body.get("max_tokens") or MAX_TOKENS), MAX_TOKENS)
    started = time.monotonic()

    if not body.get("stream"):
        upstream = await client.post("/v1/chat/completions", json=body)
        data = upstream.json()
        log_usage(label, data.get("usage"), started)
        return JSONResponse(data, status_code=upstream.status_code)

    body["stream_options"] = {"include_usage": True}
    upstream = await client.send(client.build_request("POST", "/v1/chat/completions", json=body), stream=True)
    if upstream.status_code != 200:
        await upstream.aread()
        await upstream.aclose()
        return JSONResponse(upstream.json(), status_code=upstream.status_code)

    async def relay():
        usage = None
        try:
            async for line in upstream.aiter_lines():
                if line.startswith("data: {"):
                    chunk = json.loads(line[6:])
                    usage = chunk.get("usage") or usage
                yield line + "\n"
        finally:
            await upstream.aclose()
            log_usage(label, usage, started)

    return StreamingResponse(relay(), media_type="text/event-stream")

A few decisions in there are worth calling out.

The gateway overwrites model and clamps max_tokens. Clients cannot ask for a model you did not intend to serve, and nobody can tie up the GPU with a single 30,000-token answer. A client that asks for less than the cap still gets what it asked for.

Streaming is relayed line by line, not buffered. Server-sent events are just lines of text, so the gateway reads each one from vLLM and immediately yields it to the client. The user sees the first token as soon as the model produces it. Asking vLLM for include_usage makes it send a final chunk with token counts, which is how streamed requests get logged too.

Sequence diagram: the client sends a streaming request, the gateway checks the key and limits, forwards to vLLM, then relays each data chunk back as it arrives and logs token usage at the end
Each chunk passes through as soon as vLLM emits it. Usage is logged from the final chunk.

The upstream client is created once. A shared httpx.AsyncClient keeps connections to vLLM open instead of opening a new one for every request, which matters once you are streaming dozens of responses at a time.

The rate limiter lives in memory. That is correct for a single gateway process and it is deliberately simple. If you run several gateway replicas, move the buckets into Redis so the limit is shared.

Step 3: put both behind one compose file

# docker-compose.yml
services:
  vllm:
    image: vllm/vllm-openai:v0.9.1
    command: >
      --model Qwen/Qwen2.5-7B-Instruct
      --served-model-name local-chat
      --max-model-len 8192
      --gpu-memory-utilization 0.90
    ipc: host
    volumes:
      - hf-cache:/root/.cache/huggingface
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
    restart: unless-stopped

  gateway:
    build: ./gateway
    environment:
      UPSTREAM_URL: http://vllm:8000
      MAX_TOKENS: "1024"
      RATE_PER_MINUTE: "30"
    secrets:
      - api_keys
    ports:
      - "8080:8080"
    depends_on:
      - vllm
    restart: unless-stopped

secrets:
  api_keys:
    file: ./api_keys.txt

volumes:
  hf-cache:

Notice that the vllm service has no ports: section. It is reachable from the gateway by its service name and from nowhere else. That one omission is most of the security model.

The gateway image is a slim Python image with fastapi, uvicorn and httpx installed, started with uvicorn app:app --host 0.0.0.0 --port 8080. Put a reverse proxy such as Caddy or nginx in front of port 8080 for TLS before anything outside your own network talks to it.

Step 4: use it from existing code

This is the payoff. Any code written against the OpenAI SDK works by changing two values:

from openai import OpenAI

client = OpenAI(base_url="https://llm.example.com/v1", api_key="sk-local-...")

stream = client.chat.completions.create(
    model="local-chat",
    messages=[{"role": "user", "content": "Explain KV cache in two sentences."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

The same goes for LangChain, LlamaIndex, and most editor plugins that let you set a custom OpenAI endpoint.

Before you call it production

The setup above is enough for an internal team. Before strangers rely on it, I work through this list:

  • Load test with realistic prompts. Throughput depends heavily on prompt and answer length. Replay a sample of real requests at increasing concurrency and watch time-to-first-token, not just total time.
  • Set timeouts on purpose. A long generation can legitimately take a minute or two. The gateway's read timeout, the reverse proxy's timeout and any client timeout should all agree, or streams get cut off mid-answer.
  • Watch the queue. vLLM exposes Prometheus metrics, including how many requests are running and waiting. A growing waiting count is the clearest signal that you need a second GPU or a smaller context limit.
  • Keep prompts out of the logs by default. Usage counts per key are enough for billing and debugging. Logging full prompts turns your gateway into a store of everything your users ever asked.
  • Pin versions. Pin the vLLM image tag and the model revision. An unpinned latest tag means a restart can quietly change the model's behaviour.
  • Decide what happens when the GPU is down. Either return a clear 503 that clients handle, or have the gateway fall back to a hosted provider for non-sensitive traffic. Pick one deliberately.

Was it worth it?

For steady, predictable workloads such as classification, extraction, internal assistants and agent tool calls, a single GPU running a 7–8B model handles a surprising amount of traffic, and the cost is a fixed monthly number instead of a per-token meter. More importantly, the data never leaves a machine you control, and the model only changes when you change it.

For workloads that need the very strongest model, or traffic that comes in rare, huge spikes, a hosted API is still the better deal. The nice thing about building the gateway this way is that you do not have to choose forever. Your clients talk to one OpenAI-compatible URL, and what sits behind it can change whenever the numbers do.