A Practical Guide to Building a Personal Chat Client with LLM APIs

    This guide provides a practical approach to building a personal chat client using Large Language Model (LLM) APIs. It covers selecting the right deployment topology, securing API keys through server-side proxies, implementing streaming responses via Server-Sent Events (SSE), and managing multi-turn conversation contexts efficiently.

    1. Choosing a Deployment Topology

    Your deployment topology determines where API keys are stored and whether the client can be accessed across multiple devices. Here are three common architectures:

    Topology Use Case Key Storage Main Trade-offs
    Local static page + local proxy Single user, single computer Local environment variables Accessible only on the local machine
    Static hosting + serverless function proxy Single user, multi-device access Hosting platform’s secret configuration Must verify if the function supports streaming responses and sufficient timeouts
    Full-stack application Multi-user, or requires account and data sync Server-side environment variables or Key Management Service (KMS) Requires server and database maintenance

    Choosing the right method is straightforward. If you only use one computer, choose the first. If you need mobile access, choose the second. If you need multi-user support or data synchronization, choose the third.

    For all three topologies, it is strongly advised not to let the browser call the model API directly. There are two main reasons: first, browser Cross-Origin Resource Sharing (CORS) policies will block most cross-site requests; second, your API key will be exposed in the frontend code. Therefore, requests should be sent to your own server first, which then attaches the key and forwards the request to the model service.

    2. API Key Security and Proxy Integration

    An API key is tied to your account, and usage costs are billed to that account. If a key is leaked, others can drain your quota. Adhere to the following best practices:

    • Store keys only in server-side environment variables or a KMS. Never write them into source code, frontend build artifacts, or version control repositories.
    • The frontend should only request your own proxy address. The proxy will add the Authorization header on the server side.
    • Configure a CORS whitelist for your proxy to only allow requests from your page’s domain.
    • Use HTTPS for all external services.
    • Create separate keys for different use cases, and set spending limits and billing alerts.
    • Logs should only record the request ID, status code, and latency. Do not log API keys, full request bodies, or private user data.
    • If you suspect a leak, immediately revoke the old key, generate a new one, update your environment variables, and restart the service.

    Below is a minimal proxy example running on Node.js 18 or higher, using Express. The model endpoint, API key, and model name are all read from environment variables.

    1. import express from "express";
    2. const app = express();
    3. app.use(express.json({ limit: "256kb" }));
    4. app.post("/api/chat", async (req, res) => {
    5. const { messages, max_tokens = 1024, temperature = 0.7 } = req.body;
    6. if (!Array.isArray(messages) || messages.length === 0 || messages.length > 50) {
    7. return res.status(400).json({ error: "invalid messages" });
    8. }
    9. const upstream = await fetch(process.env.MODEL_API_URL, {
    10. method: "POST",
    11. headers: {
    12. "Content-Type": "application/json",
    13. Authorization: `Bearer ${process.env.MODEL_API_KEY}`,
    14. },
    15. body: JSON.stringify({
    16. model: process.env.MODEL_NAME,
    17. messages,
    18. max_tokens: Math.min(max_tokens, 4096),
    19. temperature: Math.min(Math.max(temperature, 0), 1),
    20. stream: true,
    21. }),
    22. signal: AbortSignal.timeout(60_000),
    23. });
    24. if (!upstream.ok) {
    25. return res.status(upstream.status).json({ error: "upstream error" });
    26. }
    27. res.setHeader("Content-Type", "text/event-stream");
    28. res.setHeader("Cache-Control", "no-cache");
    29. for await (const chunk of upstream.body) {
    30. res.write(chunk);
    31. }
    32. res.end();
    33. });
    34. app.listen(3000);

    In this example, the proxy applies upper bounds to request parameters. This is a step easily overlooked during integration. Recommended parameter boundaries are as follows (refer to your specific provider’s documentation for exact limits):

    • Limit the number of messages per request to 50, and the request body size to 256KB.
    • Set an upper limit for max_tokens, typically between 1024 and 4096 for personal use.
    • Restrict temperature between 0 and 1. Values outside this range should be automatically corrected.
    • Set the upstream request timeout to 60 seconds to prevent resource consumption if the connection fails to establish.
    • If the client disconnects, the proxy should abort the upstream request simultaneously to avoid continued billing for generated content.

    3. Streaming Output and Multi-Turn Context

    3.1 Streaming Output

    To enable streaming output, set stream to true in the request. The upstream server returns data in Server-Sent Events (SSE) format, where each line begins with data:, and the final line is data: [DONE]. When reading this on the frontend, you must handle cases where a single line is split across two data chunks, otherwise JSON parsing will fail.

    1. const response = await fetch("/api/chat", {
    2. method: "POST",
    3. headers: { "Content-Type": "application/json" },
    4. body: JSON.stringify({ messages }),
    5. });
    6. const reader = response.body.getReader();
    7. const decoder = new TextDecoder();
    8. let buffer = "";
    9. while (true) {
    10. const { value, done } = await reader.read();
    11. if (done) break;
    12. buffer += decoder.decode(value, { stream: true });
    13. const lines = buffer.split("\n");
    14. buffer = lines.pop();
    15. for (const line of lines) {
    16. if (!line.startsWith("data: ")) continue;
    17. const data = line.slice(6).trim();
    18. if (data === "[DONE]") return;
    19. const delta = JSON.parse(data).choices?.[0]?.delta?.content ?? "";
    20. appendToUI(delta);
    21. }
    22. }

    If the streaming output is interrupted, you should retain the partial response received so far and mark it as incomplete in the UI. Users can click retry, and the client can resend the request with the original message list.

    If there is an Nginx server in front of your proxy, you need to disable response buffering; otherwise, the text will appear all at once. The corresponding configuration is proxy_buffering off;. If you are using a serverless function platform, you must also verify whether it supports streaming responses.

    3.2 Multi-Turn Context Control

    For multi-turn conversations, every request must include the conversation history. The system prompt is fixed as the first message, and the remaining messages are arranged in chronological order. When the history becomes too long, the oldest messages need to be truncated.

    1. function trimHistory(messages, maxChars = 12000) {
    2. const [system, ...rest] = messages;
    3. const size = (list) => list.reduce((n, m) => n + m.content.length, 0);
    4. while (rest.length > 1 && size(rest) > maxChars) {
    5. rest.shift();
    6. }
    7. return [system, ...rest];
    8. }

    The character budget should be calculated by subtracting the reserved max_tokens from the model’s context window. The token conversion ratio for Chinese characters varies by model; for rough estimates, you can assume about 1 to 2 tokens per character.