Building a Custom Chat App with APIs After Free Quota Restrictions

    This article explains how developers can build custom chat applications using LLM APIs after free quota restrictions. It covers architecture design, backend proxy implementation with FastAPI, frontend modification, cloud deployment, and strategies for cost and stability control.

    1. The Root of Quota Disputes: Service Tiering, Not Lack of Paid Channels

    Recently, a leading Large Language Model (LLM) product tightened its daily conversation quotas for web and mobile app interfaces. Heavy usage scenarios, such as role-playing and long-form content creation, were hit the hardest. Many users noticed the absence of a monthly subscription entry point in the interface, leading to complaints about wanting to pay but having nowhere to do so.

    From an operations perspective, such products typically adopt a “resource metering” model. The free tier primarily serves brand promotion, habit building, and lightweight usage, with costs controlled through rate limiting and daily quota caps. The channel for high-frequency demands is the API, and the billing and architecture for both are generally isolated. Therefore, a simple free-tier interface does not mean the service provider lacks a commercialization strategy; it simply means the payment gateway is located elsewhere.

    The experience difference between a subscription model and API pay-as-you-go billing is also distinct. A subscription is an “all-inclusive” price where users do not need to understand billing details. API pay-as-you-go requires monitoring token consumption, concurrency, and unit pricing, which presents a barrier for non-technical users. For users with development capabilities, the advantage of pay-as-you-go is that costs are directly tied to actual usage; during low-frequency periods, there is no need to pay for idle quotas.

    2. Solution Overview: Open-Source Frontend, Keys Stay on the Server

    If your goal is to continue using the model beyond the free quota, consider the following architecture:

    • Frontend: Use an open-source chat frontend project to handle the UI and conversation interaction.
    • Backend Proxy: Deploy a lightweight service to receive frontend requests, attach the API key, and forward them to the model service provider.
    • Model API: Billed based on actual call volume.

    A critical principle here is: The browser must not hold a long-term API key. Embedding the key in frontend code, build artifacts, or localStorage allows anyone who opens developer tools to extract it, potentially leading to massive charges. Calling the model API directly from the browser also encounters Cross-Origin Resource Sharing (CORS) restrictions, and service providers may not permit such usage anyway.

    1. Backend Proxy Example

    Below is a minimal example using Python and FastAPI. The API key and access token are read from environment variables:

    1. import os
    2. import hmac
    3. import httpx
    4. from fastapi import FastAPI, Header, HTTPException
    5. from fastapi.middleware.cors import CORSMiddleware
    6. API_KEY = os.environ["LLM_API_KEY"] # LLM provider API key, stored only on the server
    7. API_BASE = os.environ.get("LLM_API_BASE", "https://api.example.com/v1")
    8. ACCESS_TOKEN = os.environ["PROXY_ACCESS_TOKEN"] # Proxy access token, used to block unauthorized calls
    9. ALLOWED_ORIGIN = os.environ.get("ALLOWED_ORIGIN", "http://localhost:8080")
    10. MAX_TOKENS_CAP = 1024 # Max output tokens per request, controls cost
    11. app = FastAPI()
    12. app.add_middleware(
    13. CORSMiddleware,
    14. allow_origins=[ALLOWED_ORIGIN],
    15. allow_methods=["POST"],
    16. allow_headers=["Authorization", "Content-Type"],
    17. )
    18. @app.post("/chat")
    19. async def chat(body: dict, authorization: str = Header(default="")):
    20. expected = f"Bearer {ACCESS_TOKEN}"
    21. if not hmac.compare_digest(authorization, expected):
    22. raise HTTPException(status_code=401, detail="unauthorized")
    23. # Only forward whitelisted fields to prevent arbitrary frontend parameter modifications
    24. payload = {
    25. "model": body.get("model", "default-model-name"),
    26. "messages": body.get("messages", [])[-20:], # Limit context turns
    27. "max_tokens": min(int(body.get("max_tokens", 512)), MAX_TOKENS_CAP),
    28. }
    29. async with httpx.AsyncClient(timeout=60) as client:
    30. resp = await client.post(
    31. f"{API_BASE}/chat/completions",
    32. headers={"Authorization": f"Bearer {API_KEY}"},
    33. json=payload,
    34. )
    35. if resp.status_code != 200:
    36. raise HTTPException(status_code=502, detail="upstream error")
    37. return resp.json()

    The endpoint paths, model names, and request formats should follow the provider’s official documentation. The api.example.com in the example is a placeholder and must be replaced.

    2. Frontend Modification

    Change the target address for model API requests in the open-source frontend to your own proxy address, such as https://your-proxy.example.com/chat. The frontend no longer needs to store the model key. If the project originally required entering an API key in the settings page, you should remove this input field or only retain the proxy address field.

    When debugging locally, do not simply double-click index.html. Opening the page via file:// makes the browser’s Origin unstable, making CORS configuration difficult. It is recommended to start a local static server, such as using python -m http.server 8080, and set ALLOWED_ORIGIN to http://localhost:8080.

    3. Limitations of the Access Token

    The ACCESS_TOKEN in the example will appear in the frontend request headers. It can prevent random network requests from draining your quota, but it cannot stop someone who has accessed your page from using it. If it is only for your own use or a few colleagues, this is sufficient. If you intend to open it to multiple users, you should switch to a proper authentication system and allocate independent quotas to each user.

    3. Cloud Deployment and Access Control

    Frontend static files can be hosted on object storage static website hosting or a CDN, as they only contain page code. The proxy service should be deployed in a cloud function or container service, meeting the following requirements:

    • Keys must be injected via the platform’s environment variables or a secret management service, not hardcoded into the code repository.
    • Expose only HTTPS externally.
    • Set up authentication for the proxy endpoint; anonymous calls should not be allowed.
    • Do not log full conversation contents or keys; apply desensitization if necessary.

    If you want to achieve multi-device synchronization, such as syncing chat history between a computer and a mobile phone, you can store the records in object storage or a database. In this case, you must first determine the storage location, retention period, and deletion methods, as conversation content may contain personal or business-sensitive information.

    Additionally, open-source frontend projects typically come with a license. You need to verify whether the license allows modification and deployment, and whether it requires retaining copyright notices. If you plan to distribute the modified version publicly, check the license requirements. Do not directly copy the official brand assets and UI materials to a public service to avoid copyright or trademark issues.

    4. Cost and Stability Control

    The biggest risk of pay-as-you-go billing is runaway costs. It is recommended to implement at least the following:

    1. Token Estimation: Record the input and output token counts for each request on the proxy side and calculate costs based on the model’s unit price.
    2. Budget Alerts: Set monthly spending caps and alert thresholds in the provider’s console, and confirm the handling method for overages.
    3. Per-User Rate Limiting: Limit the number of requests per minute and per day for each user.
    4. Timeouts and Retries: Set reasonable timeout durations. Retry limits must be capped to avoid repeated billing during outages.
    5. Context Trimming: Long conversations continuously accumulate input tokens; you should truncate to recent turns or generate summaries.

    5. Comparing Alternative Solutions

    Whether to build your own solution depends on usage frequency, privacy requirements, and technical investment. The comparison below provides general guidance; specific prices and terms are subject to the latest announcements from each service provider.

    Solution Cost Characteristics Privacy & Data Experience Target Audience
    Official subscription or free tier Fixed monthly fee or free quota, restricted when exceeded Data processed by provider, bound by their terms Mature UI, fast feature updates General users with stable usage
    API pay-as-you-go + self-built frontend Proportional to usage, fine-grained control Logs and storage location controllable, but must follow API terms Customizable, requires maintenance Users with dev skills and fluctuating usage
    Local open-source models Upfront hardware investment, low marginal cost later Data stays local Depends on model and hardware, varies greatly Users with high privacy needs and good hardware

    From a technical and commercial perspective, service providers have several possible evolution directions, though these are purely speculative:

    1. Hybrid Billing: Retain API pay-as-you-go billing while offering monthly packages for individual users. The package includes a certain quota, with throttling or queuing applied once exceeded.
    2. Bundled Membership: Selling model capabilities as part of a bundled service alongside other products, rather than offering chat subscriptions standalone.

    Regardless of the direction the provider chooses, developers should avoid betting their business entirely on a single free quota or a single price point.

    Conclusion

    The tightening of free quotas is a common adjustment as the industry shifts from scale-driven acquisition to refined operations. For developers, API pay-as-you-go combined with a self-built frontend provides an independent calling channel separate from the free tier. However, it does not bring “unlimited usage” but rather direct responsibility for costs, keys, and data.

    When implementing this, remember three key points: keep keys only on the server side, set caps on costs, and establish clear rules for chat data storage and deletion. By adhering to these principles, a self-built solution can be used stably and controllably.