Low-Cost LLM API Usage: Building a Secure, Controllable Chat Frontend

    As free chat tiers become tighter, developers can combine paid LLM APIs with a self-hosted chat frontend to gain flexibility and more predictable costs. This article first compares the token cost of keeping the full conversation history versus trimming it, then provides a runnable Node.js proxy that keeps API keys on the server. It also covers streaming SSE parsing, multi-model aliasing, context trimming, usage tracking, and the changes needed before opening the service to public users.

    1. Background: A Self-Hosted Frontend Is a Controllable Path After Free Tiers Tighten

    Recently, many developers have noticed queuing, rate limiting, or unavailability during peak hours on some LLM vendors’ free chat services. Free chat pages are mainly used for customer acquisition and experience, while inference compute costs remain significant. As user scale grows, vendors naturally allocate more resources to paid APIs.

    For developers, calling APIs directly and adding a self-hosted chat frontend is another path. It offers more flexibility, and costs are easier to estimate. This article first clarifies the billing logic, then provides runnable backend proxy code, and finally explains streaming output parsing, multi-model adaptation, context trimming, and usage tracking.

    2. Cost First: Full History vs. Trimmed History

    APIs are billed by token. A token is the basic unit of text processed by a model. For estimation, you can conservatively assume that about one Chinese character corresponds to one token. The actual value depends on each model’s tokenizer; for formal accounting, use the vendor’s tokenizer tool or billing documentation.

    The cost of a single turn can be expressed as:

    Single-turn cost = input tokens × input price + output tokens × output price

    The following example uses assumed data. The input price is 1 yuan per million tokens, and the output price is 4 yuan per million tokens. The system prompt is about 50 tokens, each user question is about 300 tokens, and each model reply is about 500 tokens. After each completed turn, history increases by about 800 tokens, i.e., question plus reply. These prices are illustrative only. When using this in practice, replace them with the vendor’s current price list and record the date of the query, because prices and usage can change.

    The input for each turn consists of three parts:

    Current-turn input = system prompt 50 + history messages + current question 300

    When the full history is retained, the history for turn n is the sum of the previous n−1 turns, so the current-turn input is 350 + 800 × (n−1). When only the most recent 5 turns are retained, history is at most 5 turns, or 4,000 tokens. Therefore, from turn 6 onward, the current-turn input is fixed at 50 + 4,000 + 300 = 4,350 tokens.

    Table 1 lists values for selected turns. All values are in tokens:

    Turn Full history: current-turn input Full history: cumulative input Trim to 5 turns: current-turn input Trim to 5 turns: cumulative input
    1 350 350 350 350
    2 1,150 1,500 1,150 1,500
    3 1,950 3,450 1,950 3,450
    5 3,550 9,750 3,550 9,750
    6 4,350 14,100 4,350 14,100
    10 7,550 39,500 4,350 31,500
    20 15,550 159,000 4,350 75,000

    Taking a 20-turn conversation as an example, the output volume is the same under both strategies: 20 × 500 = 10,000 tokens, corresponding to 0.04 yuan. The input part differs significantly. With full history, cumulative input is 159,000 tokens, costing about 0.159 yuan, for a total of about 0.20 yuan. After trimming to the most recent 5 turns, cumulative input is 75,000 tokens, costing about 0.075 yuan, for a total of about 0.12 yuan.

    The more turns there are, the larger the gap becomes. With full history, cumulative input grows approximately quadratically with the number of turns. At 100 turns, cumulative input is about 4 million tokens, compared with about 420,000 tokens after trimming. After trimming, input grows roughly linearly with the number of turns.

    Two more variables matter. First, most models charge more for output than for input, so long-form generation is more expensive than short Q&A. Second, the same vendor usually offers both flagship and lightweight models; lightweight models may be much cheaper and are suitable for casual chat and simple Q&A.

    3. Architecture: Keep the Key on the Server Only

    The most common mistake in a self-hosted frontend is key management. If an API key is written into JavaScript that runs in the browser, anyone who opens the page can see it in developer tools. Once the key leaks, others can use your quota to call models, and the charges are billed to your account.

    Therefore, the recommended structure is:

    Browser page → self-hosted backend proxy → model vendor API

    The browser only sends chat messages to your own backend. The backend reads the key from environment variables, sends requests to the vendor, and forwards the streaming response to the browser. The key does not appear in frontend code, network requests, or the version repository.

    Runtime Environment and Environment Variables

    The runtime environment is as follows:

    • Node.js 18.18 or later; Node.js 20 LTS is recommended
    • express 4.21.2, express-rate-limit 7.5.0
    • The upstream API must be compatible with the OpenAI-style chat/completions format. If the vendor’s API differs, the request body and streaming parser need to be updated accordingly.

    Environment variables are described below:

    Variable Description
    UPSTREAM_URL Vendor API endpoint
    UPSTREAM_API_KEY Vendor key, used only on the server
    ACCESS_TOKEN Token for accessing this proxy; generate it with openssl rand -hex 32
    MAX_HISTORY_TURNS Number of history turns to retain; default is 5

    Backend Code

    Save the following code as server.js:

    1. import express from "express";
    2. import rateLimit from "express-rate-limit";
    3. import crypto from "node:crypto";
    4. const {
    5. UPSTREAM_URL,
    6. UPSTREAM_API_KEY,
    7. ACCESS_TOKEN,
    8. PORT = "3000",
    9. MAX_HISTORY_TURNS = "5",
    10. } = process.env;
    11. if (!UPSTREAM_URL || !UPSTREAM_API_KEY || !ACCESS_TOKEN) {
    12. throw new Error("Missing environment variables UPSTREAM_URL, UPSTREAM_API_KEY, or ACCESS_TOKEN");
    13. }
    14. const MAX_HISTORY = Number(MAX_HISTORY_TURNS);
    15. const SYSTEM_PROMPT = "You are a concise, accurate Chinese assistant.";
    16. // The frontend only sends aliases; real model names are mapped only on the server
    17. const MODELS = {
    18. "chat-fast": "vendor-small-model",
    19. "chat-pro": "vendor-large-model",
    20. };
    21. const ROLES = new Set(["system", "user", "assistant"]);
    22. const app = express();
    23. app.use(express.json({ limit: "64kb" }));
    24. app.use("/api/", rateLimit({ windowMs: 60_000, limit: 20, standardHeaders: true }));
    25. function auth(req, res, next) {
    26. const given = Buffer.from(req.get("authorization")?.replace(/^Bearer /, "") ?? "");
    27. const expected = Buffer.from(ACCESS_TOKEN);
    28. if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
    29. return res.status(401).json({ error: "unauthorized" });
    30. }
    31. next();
    32. }
    33. function validate(body) {
    34. if (typeof body?.model !== "string" || !MODELS[body.model]) return "Invalid model alias";
    35. if (!Array.isArray(body.messages) || body.messages.length === 0 || body.messages.length > 200) {
    36. return "Invalid messages count";
    37. }
    38. for (const m of body.messages) {
    39. if (!ROLES.has(m?.role) || typeof m.content !== "string" || m.content.length > 8000) {
    40. return "Invalid message format";
    41. }
    42. }
    43. return null;
    44. }
    45. // Keep only the most recent N turns and ensure the first message is from user
    46. function trimHistory(dialog) {
    47. const keep = dialog.slice(-MAX_HISTORY * 2);
    48. while (keep.length && keep[0].role !== "user") keep.shift();
    49. return keep;
    50. }
    51. app.post("/api/chat", auth, async (req, res) => {
    52. const err = validate(req.body);
    53. if (err) return res.status(400).json({ error: err });
    54. // The system prompt is decided by the server; any system messages from the client are discarded
    55. const alias = req.body.model;
    56. const dialog = req.body.messages.filter((m) => m.role !== "system");
    57. const messages = [{ role: "system", content: SYSTEM_PROMPT }, ...trimHistory(dialog)];
    58. const started = Date.now();
    59. let upstream;
    60. try {
    61. upstream = await fetch(UPSTREAM_URL, {
    62. method: "POST",
    63. headers: {
    64. "Content-Type": "application/json",
    65. Authorization: `Bearer ${UPSTREAM_API_KEY}`,
    66. },
    67. body: JSON.stringify({
    68. model: MODELS[alias],
    69. messages,
    70. stream: true,
    71. stream_options: { include_usage: true },
    72. }),
    73. signal: AbortSignal.timeout(120_000),
    74. });
    75. } catch (e) {
    76. console.error(JSON.stringify({ event: "upstream_unreachable", reason: e.name }));
    77. return res.status(502).json({ error: "upstream_unreachable" });
    78. }
    79. if (!upstream.ok) {
    80. console.error(JSON.stringify({ event: "upstream_status", status: upstream.status }));
    81. return res.status(502).json({ error: "upstream_error" });
    82. }
    83. res.set({
    84. "Content-Type": "text/event-stream; charset=utf-8",
    85. "Cache-Control": "no-cache",
    86. Connection: "keep-alive",
    87. });
    88. res.flushHeaders();
    89. const reader = upstream.body.getReader();
    90. req.on("close", () => reader.cancel().catch(() => {}));
    91. let bytes = 0;
    92. try {
    93. for (;;) {
    94. const { done, value } = await reader.read();
    95. if (done) break;
    96. bytes += value.byteLength;
    97. res.write(value);
    98. }
    99. console.log(JSON.stringify({ event: "chat_done", alias, ms: Date.now() - started, bytes }));
    100. } catch (e) {
    101. console.error(JSON.stringify({ event: "stream_broken", reason: e.name }));
    102. } finally {
    103. res.end();
    104. }
    105. });
    106. app.listen(Number(PORT), () => console.log(`listening on ${PORT}`));

    If the vendor does not support stream_options, remove that field from the request body; usage tracking then needs to be handled separately.

    Start and Test

    1. npm init -y
    2. npm pkg set type=module
    3. npm i express@4.21.2 express-rate-limit@7.5.0
    4. export UPSTREAM_URL="https://api.example.com/v1/chat/completions"
    5. export UPSTREAM_API_KEY="your-vendor-key"
    6. export ACCESS_TOKEN="$(openssl rand -hex 32)"
    7. export MAX_HISTORY_TURNS=5
    8. node server.js

    Open another terminal and test:

    1. curl -N -X POST http://localhost:3000/api/chat \
    2. -H "Authorization: Bearer $ACCESS_TOKEN" \
    3. -H "Content-Type: application/json" \
    4. -d '{"model":"chat-fast","messages":[{"role":"user","content":"Hello"}]}'

    The -N flag disables curl output buffering so you can see the response arrive in chunks.

    Code Notes

    Token comparison uses timingSafeEqual to prevent attackers from guessing the token bit by bit through response timing. The system prompt is set by the server; even if the client sends system messages, they are discarded, preventing the frontend from arbitrarily changing model behavior. The default rate limit is 20 requests per IP per minute and can be adjusted based on actual usage. The timeout is set to 120 seconds for the entire request; it can be increased for very long answers. Logs record only the model alias, elapsed time, and byte count, not message content or keys.

    4. Streaming Output Parsing

    Upstream APIs usually return streaming data in Server-Sent Events format. Each event is a line starting with data:, followed by a JSON object. New text is located at choices[0].delta.content. After all content has been sent, the API returns a line data: [DONE].

    Network chunks do not align with line boundaries. A line of text may be split across two reads, so the parser must buffer incomplete content and process only complete lines. The following is a browser-side parsing function:

    1. export async function streamChat({ token, alias, messages, onToken, onUsage }) {
    2. const res = await fetch("/api/chat", {
    3. method: "POST",
    4. headers: {
    5. "Content-Type": "application/json",
    6. Authorization: `Bearer ${token}`,
    7. },
    8. body: JSON.stringify({ model: alias, messages }),
    9. });
    10. if (!res.ok) throw new Error(`Request failed HTTP ${res.status}`);
    11. const reader = res.body.getReader();
    12. const decoder = new TextDecoder();
    13. let buffer = "";
    14. let finished = false;
    15. while (!finished) {
    16. const { done, value } = await reader.read();
    17. if (done) break;
    18. buffer += decoder.decode(value, { stream: true });
    19. const lines = buffer.split("\n");
    20. buffer = lines.pop(); // The last line may be incomplete; keep it for the next chunk
    21. for (const line of lines) {
    22. if (!line.startsWith("data:")) continue;
    23. const data = line.slice(5).trim();
    24. if (data === "[DONE]") {
    25. finished = true;
    26. break;
    27. }
    28. let json;
    29. try {
    30. json = JSON.parse(data);
    31. } catch {
    32. continue; // Ignore a single corrupted line instead of aborting the whole answer
    33. }
    34. const text = json.choices?.[0]?.delta?.content;
    35. if (text) onToken(text);
    36. if (json.usage) onUsage?.(json.usage);
    37. }
    38. }
    39. if (!finished) throw new Error("Streaming connection ended unexpectedly");
    40. }

    Example usage:

    1. let answer = "";
    2. await streamChat({
    3. token: sessionStorage.getItem("token"),
    4. alias: "chat-fast",
    5. messages: [{ role: "user", content: "Explain what a token is in one sentence" }],
    6. onToken: (t) => {
    7. answer += t;
    8. render(answer); // Update the page each time a chunk arrives
    9. },
    10. onUsage: (u) => console.log(u.prompt_tokens, u.completion_tokens),
    11. });

    If [DONE] is missing, the function throws an error. This is because the proxy has already sent the HTTP status code to the browser; if the connection breaks midway, the status code can no longer be changed, so this marker is the only way to determine whether the answer is complete.

    5. Multi-Model Adaptation and Context Trimming

    The key to multi-model adaptation is to encapsulate differences on the server. The frontend only knows aliases such as chat-fast and chat-pro. The server’s MODELS object maps aliases to the vendor’s real model names. Adding a model requires changing only this one place.

    Different models may have different parameters. For example, some models use max_tokens, while others use max_completion_tokens; some do not support temperature. Such differences should be handled in one function, with each alias corresponding to a set of parameters. The calling side remains unchanged, so switching models does not require modifying page code.

    The goal of context trimming is to control input volume per turn. The trimHistory function in the code cuts by turns and retains the most recent MAX_HISTORY_TURNS turns. Trimming by turns is simple and reliable, but turn lengths can vary widely. If someone pastes a very long article, trimming by turns will still keep it. A more precise approach is to trim by token budget: accumulate from the newest message backward and stop when the budget is exceeded.

    Trimming loses early information. If a conversation needs long-term context, you can use a cheap lightweight model to compress old messages into a summary when a threshold is exceeded, then place the summary after the system prompt. The summary itself is also billed, so compare its cost with keeping full history before deciding whether to adopt it.

    6. Usage Tracking

    Usage tracking serves two purposes. First, it helps reconcile bills and confirm whether code estimates match vendor charges. Second, it helps detect anomalies, such as a page calling in a loop or a user consuming a large amount of quota.

    Tracking needs two types of data. The first is elapsed time, model alias, and whether the request succeeded; these are already in server logs. The second is token usage, which the vendor returns in the final event of the stream, in the form {"choices":[],"usage":{"prompt_tokens":...,"completion_tokens":...}}. When forwarding, the proxy can also decode each chunk, find the data line containing usage, and record it.

    With token counts, cost can be calculated with the following function. The unit prices need to be filled in with the vendor’s current prices:

    1. const PRICE = { "chat-fast": { input: 1, output: 4 } }; // yuan per million tokens, example values
    2. function costOf(alias, usage) {
    3. const p = PRICE[alias];
    4. return (usage.prompt_tokens * p.input + usage.completion_tokens * p.output) / 1_000_000;
    5. }

    Using the 20-turn full-history example from Section 2, cumulative prompt_tokens is 159,000 and cumulative completion_tokens is 10,000. The cost is (159000 × 1 + 10000 × 4) / 1000000 = 0.199 yuan.

    For recording, it is recommended to aggregate by day and save the model alias, request count, input tokens, output tokens, and estimated cost. At the end of each month, compare these figures with the vendor bill. If the gap is significant, it is usually caused by tokenizer assumptions or price version changes, so recheck the pricing page. Vendor consoles generally also support budget alerts; it is advisable to enable them as well.

    7. Changes Needed Before Public Access

    The code above uses a single access token and is suitable only for personal or small-scale use. The token is still visible in the browser, and anyone who obtains it can call your quota. To open the service to public users, the following items need to be added.

    First, switch to a proper login and session mechanism. For example, use OAuth or OIDC with third-party login, and set session cookies as HttpOnly, Secure, and SameSite. Second, set a call quota for each user, store quota data in a database, and check and deduct it before each request. Third, change the rate-limit key from IP to user ID to avoid users on the same network affecting each other. Fourth, restrict cross-origin sources and allow only your own frontend domain to access /api/.

    Fifth, rotate upstream keys regularly. The process is to create a new key in the vendor console, update the server environment variable and restart, confirm that requests work normally, and then revoke the old key. Sixth, do not log message bodies, access tokens, or keys; use request IDs to correlate troubleshooting when issues occur. Seventh, set a monthly budget and anomaly alerts for the vendor account so that sudden cost increases can be handled promptly.

    8. Troubleshooting Checklist

    Symptom Possible cause and handling
    Returns 401 The Authorization header format is wrong, or the token does not match the server. Confirm the format is Bearer token.
    Returns 502 and logs show upstream_status The upstream URL or key is incorrect, or the model name does not exist. Use curl to call the vendor API directly to verify.
    Returns 429 The rate-limit threshold has been exceeded. Increase limit, or add a sending interval on the frontend.
    Streaming output stops midway The reverse proxy has buffering enabled. For Nginx, set proxy_buffering off and increase proxy_read_timeout appropriately.
    The page does not display text incrementally and instead appears all at once This is also a buffering issue. Check the proxy layer and confirm the response headers include Cache-Control: no-cache.
    Bill is significantly higher than the estimate Check whether history trimming is disabled, or whether there are long outputs without a limit. Verify prompt_tokens