LLM Application Development in Practice: Technical Roadmap and Engineering Practices for Rebuilding an Intelligent Chat Platform from Scratch
This article presents a practical case study of rebuilding an intelligent chat platform using large language model APIs. It covers requirements analysis, architecture design, streaming response handling, Markdown and code rendering, context management, multi-model adaptation, evaluation methods, engineering hardening, and common pitfalls. Readers can learn the core abstractions and implementation considerations needed to move from a basic chat page to a maintainable and iterable LLM application.
1. Project Background and Goal Definition
As large language model capabilities continue to evolve, building conversational products for end users has become a common entry point for enterprise intelligent transformation. This article uses a typical “intelligent chat platform rebuild” project as a case study to outline the full process from requirements analysis to engineering implementation. “Rebuild” here does not mean simply copying a user interface. Instead, it means independently implementing a web application with core functionality based on publicly available interaction logic and API specifications, such as multi-turn dialogue, code highlighting, streaming output, and history management. This process can both validate a developer’s command of LLM APIs and expose real difficulties in engineering implementation.
At the beginning of the project, three deliverables need to be defined: first, a product functional document and structure diagram for organizing the information architecture; second, a runnable chat page that implements basic interaction; third, an enhanced version after experience optimization that incorporates personal understanding of usability. The entire development process uses two rounds of prompt-driven development: the first round describes only the requirements, and the second round adds the API key and invocation details. This design aims to simulate the rhythm of real development, where requirements are understood first and resources are connected later, while also observing how different models handle ambiguous tasks.
2. Requirements Analysis and Functional Breakdown
Before writing code, requirements must be organized. A qualified intelligent chat web client should include at least the following modules:
- Session management: Support creating, switching, and deleting multiple conversation sessions, with each session independently maintaining message context.
- Message display: Distinguish user messages from assistant replies and support Markdown rendering, code block highlighting, and mathematical formula display.
- Streaming transmission: LLM generation results are usually returned in a streaming manner. The frontend needs to render them in real time through SSE or WebSocket to improve interaction experience.
- Parameter configuration: Provide adjustment options such as temperature and maximum length to meet generation preferences in different scenarios.
- History records: Use local persistence such as IndexedDB or localStorage to ensure that data is not lost after page refresh.
- Error handling: Handle network timeouts, API rate limiting, model exceptions, and other scenarios with friendly prompts.
Based on these functions, an information architecture diagram can be drawn: the top level is an “entry page” containing the session list and the main chat area; the left sidebar handles session operations, and the right main area contains the message list and input box; the input box supports multi-line input and shortcut sending, with Enter to send and Shift+Enter for a new line. The structure diagram should reflect the data flow relationships between components. For example, message state is managed uniformly by a Store, and input and rendering are decoupled through event-driven design.
3. Technology Selection and Architecture Design
Considering rapid iteration and ecosystem maturity, the frontend is recommended to use React or Vue, together with a state management library such as Redux or Pinia and a CSS solution such as Tailwind or CSS Modules. The communication layer can use the Fetch API combined with ReadableStream to handle streaming responses, or use a mature SSE library. If a lightweight backend approach is adopted, Node.js with Express or Koa can be used as a proxy service to forward requests, inject API keys, and unify error codes. Note that API keys must not be exposed directly in the browser.
The overall architecture is divided into three layers:
- Presentation layer: Responsible for UI rendering, user interaction, and Markdown parsing.
- Application layer: Manages session state, message sequences, and parameter configuration, and maps internal data structures to API request bodies.
- Proxy layer: Forwards HTTP requests, handles authentication, timeouts, retries, and logging, and can optionally perform sensitive-word filtering.
To ensure code maintainability, clear interfaces need to be defined. For example, the message object structure is {id, role, content, timestamp, status}, and the request body follows the messages: [{role, content}] format. In addition, API calls should be encapsulated into independent service modules to isolate business logic from underlying implementation, making it easier to replace different models or upgrade protocols later.
4. Key Implementation Points for Core Features
4.1 Handling Streaming Responses
LLM generation is usually incremental. The frontend needs to listen to the response stream, parse incremental text whenever a data chunk is received, and append it to the end of the current assistant message. Pay attention to the following points during implementation:
- Use
getReader()to read the stream and loop throughread()untildoneis true. - Use
TextDecoderto decode binary data as needed to avoid garbled Chinese characters. - Handle concurrent chunking: when reading continuously, accumulated data must be concatenated before parsing to prevent JSON truncation.
- Control rendering frequency: if text updates too quickly, use
requestAnimationFramefor throttling to avoid frequent DOM operations.
Example code:
const response = await fetch('/api/chat', { method: 'POST', body: payload });const reader = response.body.getReader();const decoder = new TextDecoder();let buffer = '';while (true) {const { done, value } = await reader.read();if (done) break;buffer += decoder.decode(value, { stream: true });const lines = buffer.split('\n');buffer = lines.pop(); // Keep the incomplete linefor (const line of lines) {if (line.startsWith('data:')) {const data = JSON.parse(line.slice(5).trim());updateMessageContent(data.delta);}}}
4.2 Markdown and Code Block Rendering
To avoid security risks such as XSS, innerHTML must not be used directly. A recommended approach is to first parse content into HTML using marked or markdown-it, and then use DOMPurify for whitelist filtering. Code highlighting can use highlight.js or prism.js, with the highlighting function called dynamically after rendering is complete. For long code blocks, a “copy” button and line numbers should also be provided to improve the developer experience.
4.3 Context Management
The context of multi-turn dialogue needs to be carefully designed. One approach is to carry the entire session history with each request, but token overhead grows as the number of turns increases. In real projects, a sliding window strategy can be used: keep the most recent N messages, or compress based on roles such as system, user, and assistant. In addition, static information such as the current time and user preferences can be injected into the system prompt to make model responses more context-appropriate.
4.4 Multi-Model Adaptation
The original tests used multiple sets of different models and inference frameworks to evaluate the response effects of different underlying implementations. In real engineering, we may face the need to integrate multiple API providers or different model specifications from the same provider. It is recommended to design a unified adaptation layer, define a standard interface such as generate(messages, params), and implement a corresponding Adapter for each backend. This way, upper-layer business logic does not need to perceive differences and can switch flexibly. Evaluation dimensions can include first-token latency, generation speed, semantic coherence, error frequency, and instruction following.
5. Evaluation Methods and Iterative Optimization
After completing the first version of the rebuild, strict evaluation is required. The original experiment introduced a “two-round prompt” mechanism: the first round provides only the requirements document, and the second round reveals the API key. This can simulate how different teams perform when information is incomplete. In actual evaluation, a standardized test set should be established to cover the following scenarios:
- Basic Q&A: Factual questions to verify correctness.
- Multi-turn dialogue: Continuous follow-up questions to verify context retention.
- Code generation: Requests to write functions to verify syntax and logic.
- Long-text understanding: Input documents exceeding the model window to observe whether truncation or missed reading occurs.
- Security boundaries: Prompt injection and malicious instructions to verify whether the model provides protection.
Evaluation results can be used to drive improvements. For example, if a model loses early information in long conversations, the context window strategy can be adjusted; if responses are too verbose, the system prompt can be optimized or the temperature parameter adjusted. The original experiment showed that some models performed only minimal tests after receiving the key, while others proactively executed deeper tests and found defects. This suggests that in engineering development, an automated regression testing mechanism should be established rather than relying on manual spot checks.
6. Engineering Enhancements and Experience Optimization
On top of the basic version, the application can be enhanced in the following areas:
- Network fault tolerance: Add retry mechanisms with exponential backoff, handle 5xx and 429 errors, and provide a “regenerate” button.
- Performance monitoring: Record the latency and token consumption of each request and display them to users or administrators.
- Response cancellation: When the user stops generation or switches sessions, interrupt the request through
AbortControllerto save resources. - Keyboard shortcuts and accessibility: Support keyboard shortcut operations and add ARIA labels to buttons.
- Mobile adaptation: Use responsive layouts, automatic height adjustment for the input area, and touch debounce.
- Data export: Allow users to export sessions as Markdown or JSON for sharing.
In addition, for the “improved DeepSeek web page” deliverable, personalized design is recommended: for example, message search, tag categorization, multiple theme color schemes, and custom system prompts. These features were not mentioned in the original requirements, but they are key to improving user retention.
7. Common Pitfalls and Recommended Solutions
- API key leakage risk: Never write API keys into frontend code. Use a proxy service or cloud function for forwarding. If local development requires it, the key can be stored in environment variables and injected through Vite’s
import.meta.env, but production environments still require a backend proxy. - State inconsistency after streaming interruption: Maintain a
statusfield such asgenerating,completed, orerror, and roll back to the successful state when interrupted. - Context too long: When accumulated tokens exceed the model limit, truncation or summarization is needed. A lightweight model can first compress the history, and then the summary can be used as part of the context.
- Concurrent request race conditions: When users send multiple messages quickly, ensure ordered responses or use request IDs for matching to avoid cross-rendering.
8. Conclusion
Moving from “rebuilding a chat page” to “building a maintainable and iterable intelligent application” involves frontend engineering, API design, model adaptation, performance optimization, and many other areas. By breaking down requirements, architecture, implementation, and evaluation in detail, this article demonstrates a general methodology. LLM APIs from any cloud vendor follow a similar pattern. Developers should grasp the core abstractions: streaming input and output, multi-turn context management, and reliable error handling, rather than binding themselves to a specific brand. As multimodal models become more widespread in the future, handling mixed inputs such as images and audio will also need to be considered, but the underlying architecture can remain stable. I hope this article provides a clear reference for readers exploring the practical implementation of LLM applications.
