Building Your Own LLM Chat Client: Options Beyond Free Usage Limits

    Free tiers of large language model services usually come with daily quotas, rate limits, and output caps. This article explains why these limits exist, compares subscription plans with usage-based API billing, and walks through three deployment options for a self-hosted chat client — local, cloud static hosting with a backend proxy, and containerized with load balancing. It includes practical guidance on protecting your API key, avoiding CORS issues, and a hardened FastAPI proxy example with token verification, model whitelisting, rate limiting, and CORS controls.

    1. Why Free Usage Limits Exist

    Running large language model inference requires substantial GPU capacity. Every request consumes GPU memory and compute time, and the more concurrent requests a platform handles, the harder it becomes to keep the per-request cost down. When free-tier users grow quickly, platforms struggle to maintain the same response quality for everyone, so a common practice is to impose limits on the free web interface — such as daily request counts, per-minute rate limits, or caps on single-response length. These restrictions mainly exist to protect service stability for paying users and enterprise API customers.

    The limits apply only to free access points; they do not mean the platforms are free of charge. Most platforms monetize in two main ways, which differ primarily in billing unit and use case.

    2. Subscription Plans vs. Usage-Based API Billing

    Comparison Subscription Usage-Based API
    Billing unit Fixed monthly or annual fee Charged by input and output tokens
    Best for Individual users with light to moderate daily chatting Developers, users who need customization, and enterprises
    Cost predictability Fixed cost, but features may be capped once the plan’s limits are hit Pay as you go, but costs become hard to estimate at high volume
    Customization Limited to what the platform’s UI offers Custom system prompts, knowledge base integration, workflow integration
    Main risk You keep paying even when you barely use it If your API key leaks, others can drain your quota

    For specific prices and plans, refer to what each platform publishes on its official website; this article does not quote specific figures.

    Which option to choose depends mainly on your usage volume and technical ability. At low usage, a subscription is simpler. At high usage — or when you need to embed chat capabilities into your own systems — usage-based billing is more flexible. Neither option is strictly better than the other.

    3. Three Deployment Options for a Self-Hosted Client

    Option 1: Run locally. Both the frontend page and the proxy service run on your own computer. Suitable when you only need access from your local machine.

    Option 2: Cloud static hosting plus a backend proxy. The frontend is hosted on object storage while the proxy runs in the cloud. Suitable for access from phones and other devices.

    Option 3: Containerized proxy with load balancing. The proxy runs in containers behind a load balancer. Suitable for multi-user setups or scenarios with availability requirements.

    All three options share one principle: the real API key must only ever be stored on the server side. Frontend code and config files are visible to anyone who opens the page via browser developer tools, so a real key must never be written into them.

    4. Local Setup: Don’t Just Double-Click index.html

    Many tutorials tell readers to simply double-click index.html. This opens the page under the file:// protocol, and browsers impose extra restrictions on cross-origin requests for such pages, which can trigger CORS errors when calling remote APIs. Also, if the key is written into a config file, it will appear in plain text in the page source.

    A safer approach looks like this:

    1. Start a local HTTP server in the project directory, e.g. python -m http.server 8000, then open http://localhost:8000 in your browser.
    2. The frontend config file stores only the proxy address — never the real key.
    3. Run a separate local proxy process that reads the key from environment variables.

    Example frontend config file:

    1. // config.js
    2. // The frontend stores no real API key; all requests go to our own backend proxy
    3. const APP_CONFIG = {
    4. proxyUrl: "http://localhost:8080/api/chat",
    5. model: "your-model-name"
    6. };
    7. export default APP_CONFIG;

    Before running the proxy, install the dependencies and set two environment variables. UPSTREAM_API_KEY is the real key issued by the platform. PROXY_ACCESS_TOKEN is a random string you generate yourself, used to restrict who can call the proxy.

    1. pip install fastapi uvicorn httpx
    2. # Generate an access token
    3. python -c "import secrets; print(secrets.token_urlsafe(32))"
    4. export UPSTREAM_API_KEY="the key you obtained from the platform"
    5. export PROXY_ACCESS_TOKEN="the random string generated above"
    6. export ALLOWED_ORIGINS="http://localhost:8000"
    7. uvicorn proxy:app --host 127.0.0.1 --port 8080

    5. Cloud Deployment: Keep Static Pages and the Backend Proxy Separate

    When deploying to the cloud, handle the static frontend and the proxy service separately.

    1. Static hosting: Bundle the frontend files and upload them to object storage with static website hosting enabled. The bundle should contain only page code, styles, and the proxy address. Before uploading, use a search tool to confirm there is no string in the bundle starting with the platform’s key prefix. The real key must never be committed to a code repository either.
    2. Backend proxy: Deploy in a container, with the key injected via the platform’s secret management feature or environment variables. Logs should record only the request time, status code, and model name — never the request body or the key.
    3. Load balancing and alerting: Major cloud providers offer container services, load balancers, and logging services. Before going live, set a daily spending cap and quota alerts; otherwise abnormal calls can lead to significant financial losses.

    Below is a FastAPI proxy example with basic protections. It includes access token verification, a model whitelist, per-IP rate limiting, a CORS whitelist, timeout handling, and error message sanitization.

    1. # proxy.py
    2. import hmac
    3. import os
    4. import time
    5. from collections import defaultdict
    6. import httpx
    7. from fastapi import FastAPI, HTTPException, Header, Request
    8. from fastapi.middleware.cors import CORSMiddleware
    9. REAL_API_KEY = os.environ["UPSTREAM_API_KEY"]
    10. PROXY_ACCESS_TOKEN = os.environ["PROXY_ACCESS_TOKEN"]
    11. TARGET_URL = os.environ.get("UPSTREAM_URL", "https://api.example.com/v1/chat/completions")
    12. ALLOWED_ORIGINS = os.environ.get("ALLOWED_ORIGINS", "https://your-site.example.com").split(",")
    13. ALLOWED_MODELS = {"your-model-name"}
    14. RATE_LIMIT_PER_MIN = 20
    15. app = FastAPI()
    16. app.add_middleware(
    17. CORSMiddleware,
    18. allow_origins=ALLOWED_ORIGINS,
    19. allow_methods=["POST"],
    20. allow_headers=["Authorization", "Content-Type"],
    21. )
    22. _hits: dict[str, list[float]] = defaultdict(list)
    23. def check_rate_limit(client_id: str) -> None:
    24. now = time.time()
    25. recent = [t for t in _hits[client_id] if now - t < 60]
    26. if len(recent) >= RATE_LIMIT_PER_MIN:
    27. raise HTTPException(status_code=429, detail="Rate limit exceeded")
    28. _hits[client_id].append(now)
    29. @app.post("/api/chat")
    30. async def chat(request: Request, authorization: str = Header(default="")):
    31. # Verify the access token
    32. if not hmac.compare_digest(authorization.replace("Bearer ", ""), PROXY_ACCESS_TOKEN):
    33. raise HTTPException(status_code=401, detail="Unauthorized")
    34. check_rate_limit(request.client.host)
    35. body = await request.json()
    36. if body.get("model") not in ALLOWED_MODELS:
    37. raise HTTPException(status_code=400, detail="Model not allowed")
    38. headers = {"Authorization": f"Bearer {REAL_API_KEY}"}
    39. try:
    40. async with httpx.AsyncClient(timeout=60) as client:
    41. resp = await client.post(TARGET_URL, json=body, headers=headers)
    42. except httpx.TimeoutException:
    43. raise HTTPException(status_code=504, detail="Upstream timeout")
    44. # Return a sanitized error instead of leaking upstream details
    45. if resp.status_code != 200:
    46. raise HTTPException(status_code=502, detail="Upstream error")
    47. return resp.json()

    With this setup, the real API key never leaves the server side, the frontend stays free of sensitive credentials, and the proxy layer gives you a single point to enforce authentication, rate limits, and logging policies — a solid foundation whether you run the client locally or serve it to multiple users from the cloud.