Building an AI Assistant with an API and an Open-Source Front End Under Free-Tier Rate Limits

    When free web access to large language models becomes more restrictive, an API-backed assistant can provide a more flexible alternative. This guide compares local deployment, static hosting, and a self-managed backend gateway, covering API key security, authentication, rate limiting, cloud history sync, streaming responses, cost control, compliance, and common deployment mistakes.

    Understand the Rate Limits and Available Options

    Some large language model providers have recently introduced stricter limits on high-frequency conversations and long-context chats in their free web interfaces. As a result, users may experience slower or more restricted access. In some cases, personal subscription or payment options may not be available for every account or region, leaving users with limited web access.

    Providers commonly tighten free quotas because of computing costs. Long conversations, role-playing, and other high-context scenarios consume a large number of tokens. When the number of free users grows, operating costs can increase quickly. Providers may therefore prioritize resources for paying API customers. This is a common explanation, not a universal official statement. Always check the provider’s own announcements for the applicable policy.

    Different products from the same provider may also have different access models. Some regions or product lines offer personal subscriptions, while others primarily expose APIs. Before choosing a technical solution, confirm whether your account can use a subscription service. If API access is the only available option, the basic approach is to obtain an API key and use it through a separate interface.

    There are three common approaches:

    1. Run an open-source front end locally for personal use on one computer.
    2. Deploy the front end to cloud static hosting for access from both computers and mobile devices.
    3. Build a backend gateway with authentication, rate limiting, and cloud history synchronization for small teams or multi-user environments.

    The complexity increases in that order. Decide which functions you actually need before investing in a more complicated implementation.

    Option 1: Run an Open-Source Front End Locally

    Many providers publish open-source web chat interfaces on platforms such as GitHub. Some projects also include prebuilt release packages. Before using one, download the appropriate version from the official repository and verify the checksum provided on the release page, such as SHA-256, to confirm that the files have not been modified.

    After extracting the package, many users try to open index.html by double-clicking it. This may work with some versions, but it often causes problems:

    • Pages that use ES modules or client-side routing may fail to load resources under the file:// protocol.
    • Browsers apply strict CORS rules to requests originating from file:// pages, which can cause API requests to fail.
    • Browser LocalStorage is separated by protocol, host, and port. When you switch from file:// to http://localhost, existing chat history may not appear automatically.

    A more reliable approach is to start a local static server. From the extracted directory, run:

    1. python -m http.server 8080

    Then open http://localhost:8080 in your browser. If Node.js is installed, you can also use tools such as npx serve.

    In the application settings, enter the API key and verify that the endpoint and model name match the provider’s documentation. An incorrect model name is a common cause of failure, and the API response usually indicates what is wrong.

    Migrating Chat History

    Some versions support importing chat records in JSON format. Because the JSON structure may differ between releases, back up the original data before importing and test with a small sample first. If an import fails, avoid repeatedly retrying it. Check the version documentation and compare the expected field structure.

    Import compatibility depends on the specific front-end version. You should not assume that every existing conversation can be restored completely.

    Option 2: Deploy the Front End to Static Cloud Hosting

    A front-end build is usually a collection of static files that can be hosted in object storage or on a static website hosting service, such as the static website hosting feature of Baidu AI Cloud BOS. After deployment, the same link can be opened from both desktop and mobile browsers.

    Before publishing the site, address the following issues.

    • HTTPS: Browsers may block or restrict HTTP-only pages, and API keys can be exposed during transmission. Most hosting services support free or paid certificates, but HTTPS must be enabled in advance.
    • CORS: If the API gateway and front end use different domains, the gateway must explicitly allow requests from the front-end domain. Do not allow every origin.
    • Domain and regional requirements: Custom domains may be subject to registration, verification, or other local requirements depending on the hosting region and provider. Check the hosting provider’s current rules.
    • Access control: If the link is public, anyone can open the page and consume your quota. At minimum, add authentication, an access password, or the access-control features provided by the cloud platform.
    • Costs: Storage, bandwidth, CDN usage, and domain registration may all incur charges. API calls are billed by token usage, and frequent conversations can cost more than expected. Set budget alerts where available.

    The most important rule is simple: never place an API key in front-end code or static files. Anyone who opens the browser developer tools can inspect the front-end code and retrieve the key. If the page needs an API key to function, introduce a backend gateway and keep the key on the server.

    A CDN can improve the loading speed of static assets, but it provides limited acceleration for API calls. The response time of a large language model API is mainly determined by the model and upstream service.

    A progressive web app, or PWA, can allow users to add the site to a mobile home screen and launch it like an app. However, PWA support requires HTTPS and correctly configured service workers. Before making this change, verify that the caching strategy will not cause users to see outdated versions for an extended period.

    Option 3: Build a Backend Gateway with Authentication

    If multiple people need to use the assistant, or if you need quota controls and API key protection, place a backend gateway between the front end and the model API. The gateway has three main responsibilities:

    1. Verify the user’s identity.
    2. Add the server-side API key when requesting the model.
    3. Return the model response to the front end.

    The following example uses Node.js and Express. It implements JWT authentication, rate limiting, a CORS allowlist, and sanitized error responses. The login endpoint is not included. In a production project, use a library such as bcrypt to store password hashes and configure an expiration time for JWTs.

    1. const express = require('express');
    2. const cors = require('cors');
    3. const rateLimit = require('express-rate-limit');
    4. const jwt = require('jsonwebtoken');
    5. const app = express();
    6. app.use(express.json({ limit: '1mb' }));
    7. // Only allow requests from your own front-end domain
    8. app.use(cors({ origin: process.env.FRONTEND_ORIGIN }));
    9. // Load all secrets and configuration from environment variables
    10. const LLM_API_KEY = process.env.LLM_API_KEY;
    11. const LLM_API_ENDPOINT = process.env.LLM_API_ENDPOINT;
    12. const LLM_MODEL = process.env.LLM_MODEL;
    13. const JWT_SECRET = process.env.JWT_SECRET;
    14. // Allow up to 20 requests per IP address per minute
    15. const limiter = rateLimit({ windowMs: 60 * 1000, limit: 20 });
    16. function authMiddleware(req, res, next) {
    17. const header = req.headers['authorization'] || '';
    18. const token = header.startsWith('Bearer ') ? header.slice(7) : '';
    19. try {
    20. req.user = jwt.verify(token, JWT_SECRET);
    21. next();
    22. } catch (err) {
    23. res.status(401).json({ error: 'unauthorized' });
    24. }
    25. }
    26. app.post('/api/chat', limiter, authMiddleware, async (req, res) => {
    27. const { messages } = req.body;
    28. if (!Array.isArray(messages) || messages.length === 0) {
    29. return res.status(400).json({ error: 'invalid messages' });
    30. }
    31. try {
    32. const upstream = await fetch(LLM_API_ENDPOINT, {
    33. method: 'POST',
    34. headers: {
    35. 'Content-Type': 'application/json',
    36. 'Authorization': `Bearer ${LLM_API_KEY}`,
    37. },
    38. body: JSON.stringify({
    39. model: LLM_MODEL,
    40. messages,
    41. stream: false,
    42. }),
    43. });
    44. if (!upstream.ok) {
    45. throw new Error(`upstream status ${upstream.status}`);
    46. }
    47. res.json(await upstream.json());
    48. } catch (err) {
    49. // Log the detailed cause, but return only a short message to the client
    50. console.error('llm request failed:', err.message);
    51. res.status(502).json({ error: 'upstream service error' });
    52. }
    53. });
    54. app.listen(3000, () => console.log('gateway started'));

    Several implementation details are important:

    • JWT_SECRET must be long and randomly generated. Do not use a placeholder value from an example, and rotate it periodically.
    • Rate limiting in this example is based on IP address, which is suitable for simple deployments. In a multi-user environment, quota accounting should preferably be based on user accounts, with usage stored in a database.
    • Message length must be controlled. The 1mb request-body limit is only a basic safeguard. A production implementation should also limit the token count of each conversation to prevent unexpectedly high costs.
    • Error sanitization means that detailed causes can be written to server logs, but raw upstream errors should not be returned to the browser. Such errors may reveal account, quota, or internal configuration details.
    • Key rotation involves creating a new key in the provider console, updating the server environment variables, restarting the service, verifying that requests work, and then deleting the old key. Avoid unnecessary service interruption during the transition.
    • Keys must not appear in logs, Git repositories, or front-end build artifacts. Exclude .env files with .gitignore before committing code.

    Synchronize Chat History in the Cloud

    Open-source front ends commonly store conversations in browser LocalStorage. This is simple, but a computer and a phone will each have a separate copy of the history. Cross-device synchronization requires storing conversations in a backend database.

    A basic data model could include:

    • users: id, username, password_hash, created_at
    • conversations: id, user_id, title, updated_at, deleted_at
    • messages: id, conversation_id, client_msg_id with a unique index, role, content, created_at

    Possible endpoints include:

    • POST /api/conversations: Create a conversation
    • GET /api/conversations: Retrieve the conversation list, sorted by updated_at
    • GET /api/conversations/:id/messages?after=<timestamp-or-sequence>: Retrieve messages incrementally
    • POST /api/conversations/:id/messages: Save a message and deduplicate it on the server using client_msg_id
    • DELETE /api/conversations/:id: Soft-delete a conversation by setting deleted_at

    The front end must replace synchronous LocalStorage reads and writes with asynchronous API requests. To prevent message loss during network interruptions, write outgoing messages to a local queue first and submit them in batches when connectivity returns.

    Conflict handling can follow these rules:

    • Messages are append-only. Use client_msg_id to make each message idempotent, so repeated submissions do not create duplicates.
    • Conversation titles use last-write-wins semantics, with the update time recorded.
    • Deletions use soft delete, making recovery possible and allowing other devices to learn that a conversation has been deleted.

    Synchronization adds database, backup, and privacy responsibilities. Chat content may contain personal or business information, so data should be encrypted in transit and access permissions should be restricted in the database.

    Streaming Responses: Benefits and Trade-Offs

    The example uses stream: false, which means the gateway waits for the model to generate the complete response before returning it to the front end. Users see no text while waiting, so the experience may feel less responsive than an official web interface.

    For incremental output, use Server-Sent Events, or SSE. The gateway must forward the upstream stream using the text/event-stream content type and disable buffering in intermediate layers. For example, Nginx should be configured with:

    1. proxy_buffering off

    Streaming introduces additional edge cases:

    • Some serverless platforms impose duration limits on long-lived connections and may terminate a response before generation is complete.
    • The gateway must handle clients that disconnect midway and cancel the upstream request in time to avoid unnecessary charges.
    • Streaming responses use a different format from standard responses, so the front-end parsing logic must be updated accordingly.

    If the team does not yet have the capacity to handle these details, start with non-streaming requests and add streaming after the basic functionality is stable.

    Costs, Compliance, and Risks

    Building your own interface does not provide unlimited access to a model. Review the following issues before deployment:

    • Terms of service: Read the API provider’s terms and confirm whether access through a third-party interface is allowed, especially if the service will be shared with others or offered commercially.
    • Open-source licenses: Front-end projects commonly use licenses such as MIT or Apache-2.0. Preserve the original copyright notices and license files when using or modifying the code.
    • Costs: API providers charge for input and output tokens. Long contexts increase the cost of each request. Set usage limits and budget alerts in the provider console where possible.
    • Data privacy: Conversations are transmitted to the provider’s servers. Before sending sensitive information, review the provider’s data retention and model-training policies.
    • Availability: Once you operate your own gateway, gateway failures can also interrupt access. Long-running deployments require monitoring, logs, and backups.

    A self-hosted solution provides more control, but it also creates additional operational work. For users who only need occasional access, an official subscription or a compliant third-party service may be easier to maintain than a custom deployment.

    Common Mistakes

    The following problems occur frequently:

    1. Opening index.html by double-clicking it, causing resource loading or API requests to fail.
    2. Entering an incorrect API key or using a model name that does not match the provider’s documentation.
    3. Putting the API key in front-end code or build artifacts.
    4. Failing to configure CORS on the gateway, or allowing every origin with *.
    5. Running without rate limits or usage caps, allowing anyone who discovers the link to exhaust the quota.
    6. Using a default example value for the JWT secret or never expiring tokens.
    7. Returning raw error messages to the browser and exposing internal addresses or configuration.
    8. Failing to back up chat history before migration, leaving no rollback option when an import fails.
    9. Ignoring domain configuration, HTTPS certificates, or regional hosting requirements, causing the cloud-hosted page to become inaccessible.
    10. Failing to configure budget alerts, making it difficult to detect abnormal spending.

    Checking these items one by one can prevent most common deployment failures.