Building a Custom LLM Client Using APIs and Open-Source Frontends

    This article explains how to build a custom Large Language Model (LLM) client using developer APIs and open-source frontends. It covers the differences between web and API usage, prerequisites for setup, protecting API keys with a server-side proxy, cloud hosting best practices, troubleshooting common errors, migrating chat history, and integrating AI agents.

    1. Understanding the Differences Between Usage Methods

    Web-based LLM services usually offer free quotas per account, placing payment options on a subscription page. Developer APIs bill based on token usage, available immediately after topping up. The value of a self-built client lies in separating the chat interface from model calls: you can freely modify the UI while paying only for actual API usage.

    Prerequisites for using an API include a funded account, generated keys, and an understanding of the platform’s rate limits and pricing. A self-built client does not automatically reduce costs. A long conversation can consume a massive number of tokens, so setting usage alerts in the platform backend is essential.

    The table below compares three approaches:

    Method Cost Security Maintenance Rate Limiting
    Official Web App Limited free quota; requires subscription or wait time afterward Managed by the platform None Restricted by platform’s free quota
    Open-source Frontend Directly Connecting to API Pay-per-token Key exposure risk if hardcoded in the frontend Low Restricted by API quota
    Self-built Frontend with Server Proxy Pay-per-token plus minor server costs Key stored securely on the server; access control enabled Medium; requires proxy maintenance Rate limiting and queuing can be handled at the proxy layer

    2. Prerequisites for Setup

    Confirm the following before starting:

    1. The API endpoint URL provided by the platform, and whether it supports Cross-Origin Resource Sharing (CORS) for browser requests.
    2. The API key’s permission scope to ensure it can access the required models.
    3. Account balance, pricing, and setup of usage alerts.
    4. The runtime environment for the proxy service, such as Node.js or a serverless cloud platform.
    5. A domain name and an HTTPS certificate, if public access is needed.

    3. Running the Frontend Project Locally

    Open-source frontend projects usually provide packaged files on their repository’s Release page. Download, extract, and open the entry file (e.g., index.html). While the UI displays correctly in a browser, sending requests to the model API often triggers CORS restrictions, showing errors in the browser console. This is a browser security policy, not a project flaw.

    Most model APIs do not allow direct cross-origin requests from arbitrary web pages. Therefore, even for local runs, a small proxy is required. The proxy receives the frontend request, attaches the API key on the server side, and forwards it to the model platform.

    4. Protecting API Keys with a Server-Side Proxy

    This section is the most critical part of this guide.

    Do not enter long-term API keys into frontend configuration fields, and do not write them into publicly accessible static files. Anyone who can open the webpage can extract the key using browser developer tools or by inspecting network requests.

    The correct approach is to ensure the key exists only on the server side. Below is a minimal proxy example:

    1. // Example: Server-side proxy, key read from environment variables
    2. import express from 'express';
    3. const app = express();
    4. app.use(express.json({ limit: '1mb' }));
    5. const UPSTREAM_URL = process.env.LLM_API_URL;
    6. const API_KEY = process.env.LLM_API_KEY; // Only exists in server-side environment variables
    7. app.post('/api/chat', async (req, res) => {
    8. const controller = new AbortController();
    9. const timer = setTimeout(() => controller.abort(), 60000); // Set timeout
    10. try {
    11. const upstream = await fetch(UPSTREAM_URL, {
    12. method: 'POST',
    13. headers: {
    14. 'Content-Type': 'application/json',
    15. 'Authorization': `Bearer ${API_KEY}`,
    16. },
    17. body: JSON.stringify(req.body),
    18. signal: controller.signal,
    19. });
    20. if (!upstream.ok) {
    21. console.error('Upstream returned an error', upstream.status); // Do not log key or conversation content
    22. return res.status(502).json({ error: 'Model service temporarily unavailable' });
    23. }
    24. res.json(await upstream.json());
    25. } catch (err) {
    26. console.error('Proxy request failed', err.name);
    27. res.status(500).json({ error: 'Internal server error' });
    28. } finally {
    29. clearTimeout(timer);
    30. }
    31. });
    32. app.listen(3000);

    This code is for structural illustration only. Refer to the official documentation for actual upstream URLs, request formats, and parameter names. Before going live, implement the following protection measures:

    • Access Control: The proxy must have login tokens, IP whitelisting, or restrict access to an internal network. Otherwise, anyone with the proxy URL can consume your quota.
    • Parameter Whitelisting: Restrict available model names and parameters like max_tokens at the proxy level to prevent requests from being arbitrarily scaled.
    • Least Privilege: Create a dedicated key for the proxy with only the necessary model permissions.
    • Key Rotation: If a key is suspected to be compromised, revoke it immediately in the platform backend, generate a new key, and update the server environment variables.

    The frontend only needs to request its own proxy endpoint (e.g., /api/chat), keeping the page code free of any keys. If the frontend and proxy are deployed on the same origin, CORS issues will not occur. If cross-origin, the proxy should only allow specific origins to access it, avoiding the * wildcard.

    5. Cloud Hosting Considerations

    Placing static frontend files on object storage or a CDN allows users to access them from mobile devices and computers anytime. However, since static files are public, note the following:

    • Never place API keys in static pages.
    • Deploy the proxy service in a private environment or require authentication; do not allow anonymous access.
    • Use HTTPS throughout to prevent conversation content from being intercepted during transmission.
    • If outdated pages appear after updating the frontend, it is usually due to CDN caching not being invalidated. Manually clear the cache or update the filename hash.
    • Understand the hosting service’s billing model in advance, including traffic costs and request counts.

    6. Troubleshooting Common Errors

    • CORS Errors: The frontend and API are cross-origin. Switch to a same-origin proxy or configure allowed origins only on the proxy.
    • 401 or 403: The key is incorrect, expired, or lacks permissions for the requested model. Verify that environment variables are loaded correctly.
    • 429: Rate limit triggered. Reduce concurrency, add queuing or retry intervals, and check account quotas.
    • 502 or Timeout: The upstream model is responding slowly. Adjust the timeout duration appropriately or switch to streaming output for long-text scenarios.
    • Outdated Page Version: Static resources are cached. Clear the cache or update the filename hash.

    7. Chat History Migration and Data Backup

    Many frontend projects support import and export features, but migration success depends on three factors: the export file format, the import code’s parsing logic, and browser storage policies. Frontends usually store data in LocalStorage or IndexedDB. Clearing browser data, changing devices, using incognito mode, or reaching storage limits can cause this data to be lost.

    Follow these steps for migration:

    1. Export chat history from the original platform as a JSON file and save a separate backup.
    2. Validate the JSON file to ensure it is legitimate and that the field structure matches the import feature’s requirements.
    3. Test the import with a few records first to check if message order, timestamps, and role identifiers are correct.
    4. Import all records once verified.
    5. Regularly export local data to encrypted offline storage.

    Imported history is only used for reading and searching. The model does not automatically remember this content. To continue a previous topic in a new session, you must provide the relevant content as input to the model, keeping the model’s context length limit in mind.

    Regarding privacy, conversations may contain passwords, ID numbers, customer data, or internal business information. Desensitize data before importing or migrating. Do not type passwords or keys into chat content, and avoid storing sensitive business data in unmanaged browser storage.

    8. Advanced Extension: Agent Integration

    To add Agent capabilities to your client, a common approach is adding a middleware layer between the frontend and the model API to route requests based on user intent. Below is pseudocode illustrating the structure:

    1. // Pseudocode: Routing requests by intent, for structural illustration only
    2. async function handleUserInput(prompt, userSession) {
    3. const intent = await analyzeIntent(prompt); // Intent recognition itself consumes tokens
    4. if (intent === 'code_generation') {
    5. return routeToCodingAgent(prompt, userSession);
    6. }
    7. if (intent === 'data_analysis') {
    8. return routeToDataAnalysisAgent(prompt, userSession);
    9. }
    10. return callBaseLLM(prompt, userSession);
    11. }

    This code passes session information downstream while keeping keys on the server side. Before going live, address the following:

    • Timeouts and Retries: Set maximum retry limits