A Practical Guide to Building Your Own Chat Client with LLM APIs
This guide explains how to build a custom chat client using Large Language Model (LLM) APIs to bypass service limitations and manage your own data. It covers deployment architectures, API key management and billing basics, system design with code examples, data storage and synchronization, context management strategies, and security best practices.
I. Problem Background: Why Usage Limits Affect Experience
Online chat services typically control resource consumption through several mechanisms: request rate limits, concurrency limits, maximum context length per request, and usage-based or subscription-based billing. When free quotas are exhausted or access frequency exceeds the threshold, users may experience slow responses, rejected requests, or restricted features.
For users relying on chat tools for writing, coding assistance, and data organization, such disruptions directly break their workflows. There are two common approaches to address this. The first is to adjust the service usage method, such as choosing different plans or billing methods. The second is to decouple the chat interface from the model service, allowing users to control the client and historical data themselves. This article focuses on the technical implementation of the second approach.
II. Differences Between Two Deployment Architectures
1. Local Static Page
The frontend page runs directly in the browser, and the page script calls the model API.
- Pros: Simple deployment, no server required, suitable for temporary local use by individuals.
- Cons: API keys are stored in the browser, posing a risk of leakage; history is usually only saved on the current device.
2. Cloud Hosting with Backend Proxy
Frontend static files are deployed on a static hosting service, and model requests are uniformly routed through a custom backend proxy.
- Pros: Keys are stored in server-side environment variables; allows for adding login authentication, multi-device synchronization, and usage tracking.
- Cons: Requires maintaining a backend service and basic operations work.
Choosing which architecture depends on the number of users, access scope, and data sensitivity. For single-user local use, the first option is suitable. For multi-user use or cross-device access, the second option should be chosen.
III. API Keys and Billing Basics
An API key is the credential for calling model services, equivalent to the account’s access capabilities, and should be managed as confidential information.
Pay-as-you-go is a common model in LLM services, where costs are typically related to the number of input and output tokens. A token is the basic unit the model uses to split text. The token count for text does not always perfectly match the character count; you should refer to the usage field returned by the API. Multi-turn conversations repeatedly include historical content in the context, so the more turns there are, the higher the consumption per request.
It is recommended to take the following measures to control costs:
- Set budget limits and usage alerts for your account.
- Regularly review call logs to identify abnormally high-frequency requests.
- Truncate or summarize long conversations to reduce invalid context.
IV. System Architecture Design
A complete chat client typically consists of four layers:
- UI Layer: Message list, input box, model selector, session list.
- Chat Service Layer: Assembles the request body, maintains context, and handles streaming output and errors.
- Storage Layer: Saves sessions and messages, using either browser local storage or a server-side database.
- Authentication Layer: Responsible for user login and session isolation, essential in multi-user scenarios.
Common chat completion APIs in the industry use model and messages fields to organize requests, and the response content is located in the corresponding fields of the returned structure. Refer to the specific API documentation of the service used for exact field names and parameters. Below is an example using only the standard library:
import jsonimport osimport timeimport urllib.errorimport urllib.requestAPI_URL = os.environ["MODEL_API_URL"]API_KEY = os.environ["MODEL_API_KEY"]MODEL = os.environ.get("MODEL_NAME", "")def ask_model(messages, retries=3, timeout=60):body = json.dumps({"model": MODEL, "messages": messages}).encode("utf-8")req = urllib.request.Request(API_URL, data=body, method="POST")req.add_header("Content-Type", "application/json")req.add_header("Authorization", f"Bearer {API_KEY}")for attempt in range(retries):try:with urllib.request.urlopen(req, timeout=timeout) as resp:data = json.loads(resp.read().decode("utf-8"))return data["choices"][0]["message"]["content"]except urllib.error.HTTPError as e:if e.code == 429 and attempt < retries - 1:time.sleep(2 ** attempt) # Retry with exponential backoffcontinueraiseraise RuntimeError("Retries exhausted")
This example places the key and URL in environment variables, retries with exponential backoff upon receiving a rate limit response, and raises other errors directly for the UI layer to prompt the user.
V. Key Security
- Keys should not be written into source code, frontend scripts, or configuration files. Use environment variables or secret management services exclusively.
- In a pure frontend solution, the key will be exposed in the browser, which is only suitable for temporary local use by individuals. Multi-user or public network access must go through a backend proxy.
- The backend should restrict allowed origins and set per-user rate limits for a given time period.
- Do not log full keys or personally identifiable sensitive conversation content in the logs.
VI. Chat History Storage, Import, and Export
It is recommended to standardize session data into a fixed structure for easy import, export, and migration:
{"sessions": [{"id": "session-001","title": "API Design Discussion","createdAt": "2026-11-20T09:00:00Z","messages": [{"role": "user", "content": "Please help me design a pagination API."},{"role": "assistant", "content": "You can use cursor pagination..."}]}]}
The import process is recommended to follow this order:
- Validate the JSON structure and reject files missing required fields.
- Deduplicate by session
idto avoid duplicate imports. - Sort by creation time and write to local storage.
- Check the length of individual sessions; if they exceed the model’s context limit, truncate or summarize them before sending the request.
Exporting the same structure enables backups and cross-device migration.
VII. Context Management and Fault Tolerance
The stability of long conversations primarily depends on context management strategies:
- Truncation: Keep the system prompt and the most recent messages; older content can be compressed into a summary.
- Streaming Output: Render the model’s returned content in segments to reduce the feeling of blank wait times for the user.
- Error Classification: Handle network timeouts, rate limits (429), authentication failures, and content length exceeded errors separately, providing corresponding prompts.
- Retry Strategy: Apply exponential backoff only for recoverable errors like timeouts and rate limits. Authentication errors should directly prompt the user to check their key.
VIII. Deployment and Multi-Device Sync
The recommended deployment steps are as follows:
- Install dependencies using a package manager and run the build command to generate static files.
- Deploy the static files to a static hosting service to obtain an HTTPS access address.
- Deploy the backend proxy service and configure the API URL and key in the server environment variables.
- Integrate a login system to isolate session data for each user.
- Use object storage or a relational database as the single source of truth.
The core of multi-device synchronization is a unified data source. The client records the update time or version number of each message and pulls incremental data changes upon startup. If both ends modify the same session simultaneously, you can adopt a “last modified wins” rule or keep both copies for the user to choose.
IX. Compliance and Usage Boundaries
- Comply with the terms of service and content policies of the model service used.
- Do not share keys or open the proxy service to unauthorized users.
- Do not use technical means to bypass the service provider’s limits and restrictions.
