Building a Streaming AI Chat Template with Modern Frontend Frameworks
This article presents a reusable architectural design and engineering practice for building a web-based intelligent chat template. It covers key technical concerns including streaming output handling, state orchestration, rendering pipelines for rich text, code blocks, formulas and charts, as well as theming, persistence, security and deployment. The approach is framework-agnostic and focuses on a scalable frontend architecture that decouples model integration from UI concerns, enabling developers to quickly build production-ready conversational interfaces on top of any large language model backend.
As large language model (LLM) capabilities continue to expand on the web, intelligent chat interfaces have evolved from simple “input box + message list” layouts into complete frontend systems that support streaming output, rich text rendering, code block interactions, mathematical formulas, chart visualization, and conversation persistence. This article examines a web-based intelligent chat template, abstracts its key technical challenges, and presents a reusable architectural design and set of engineering practices. The discussion is not tied to any specific framework or model vendor; instead, it approaches the problem from a general technical capability standpoint, explaining how to construct a stable and extensible chat template using modern frontend technologies.
1. Template Positioning and Design Goals
The core positioning of this template is to serve as an “out-of-the-box web-based intelligent chat foundation.” It needs to satisfy three types of requirements simultaneously. First, developers should be able to quickly connect their own LLM backend services and complete a streaming chat loop. Second, the interface should include the full interaction set expected of modern conversational products, including light and dark themes, message status indicators, code copy functionality, formula and chart rendering. Third, the project structure should be clean and easy to extend, allowing for secondary development, component replacement, and business capability expansion.
The design goals can be summarized into four points:
- Streaming-first: All responses should be presented in an incremental manner to reduce perceived waiting time.
- Safe rendering: Rich text, code, formulas, and charts must all pass through a controlled pipeline.
- Maintainable state: Conversation, message, streaming, and user settings should be managed in a layered manner.
- Deployment-friendly: Frontend static resources and backend APIs should be decoupled, making it easy to deploy on common container platforms, object storage, and cloud observability systems such as logging and monitoring.
2. Overall Architecture Layers
The system is recommended to be divided into five layers: API Adaptation Layer, State Orchestration Layer, Rendering Pipeline Layer, View Interaction Layer, and Infrastructure Layer.
The API Adaptation Layer is responsible for encapsulating streaming requests, cancellation, retries, and error normalization. The State Orchestration Layer maintains conversation lists, message lists, streaming fragments, and settings. The Rendering Pipeline Layer handles markdown parsing, code highlighting, formula rendering, and chart drawing. The View Interaction Layer manages themes, scrolling, collapsing, copying, and quick actions. The Infrastructure Layer provides local persistence, logging, configuration management, and build optimization.
The key value of this layered design lies in its ability to decouple model differences. When the backend model or API protocol changes, only the API adaptation layer needs adjustment. When new rendering capabilities are required, the rendering pipeline can be extended with plugins without affecting conversation state or view structure.
3. Framework-agnostic Technology Selection
For the build tooling, modern frontend build tools are recommended to achieve faster cold starts, better code splitting, and more refined output optimization. On the view layer, a progressive frontend framework with a routing solution can be used alongside a general-purpose desktop component library. State management can be handled with a centralized solution combined with a local persistence plugin for saving user settings. On the rendering side, a markdown parser, a code syntax highlighter, a math formula rendering plugin, and a chart rendering library can be combined.
It is important to emphasize that technology choices should serve the template’s replaceability: APIs, components, and rendering plugins should all be accessed through abstraction layers, avoiding tight coupling between business code and specific implementations.
4. Recommended Directory Structure
A clear directory structure significantly lowers maintenance costs. The following organization is recommended:
src/api/ # Streaming requests, protocol parsing, error normalizationcomponents/ # Message bubbles, code blocks, formula blocks, chart blocksviews/ # Chat page, conversation list page, settings pagestores/ # Conversation state, message state, settings staterouter/ # Page routing and guardsutils/ # Rendering pipeline, clipboard, throttling, sanitizationstyles/ # Theme variables, layout, component stylestypes/ # Message, conversation, streaming event types
Directory names should maintain generic semantics and avoid embedding specific library names into paths. The rendering pipeline should be separated under utils/render, internally split into “parse — sanitize — highlight — extended rendering” for easier unit testing and lazy loading.
5. Streaming Chat Pipeline Design
The streaming pipeline is the core of the template. The frontend initiates requests via the fetch API, uses AbortController to support user cancellation, reads the response body stream, and parses it frame by frame. For Server-Sent Events (SSE) streams, frames can be split by blank lines, extracting lines starting with data:. For other incremental protocols, normalization can be performed in the adaptation layer. Key considerations include: buffer concatenation, handling incomplete frames, end markers, error retries, and distinguishing the cancelled state from errors.
Here is a simplified code example:
type ChatMessage = {id: string;role: "user" | "assistant";content: string;reasoning?: string;status: "streaming" | "done" | "error";};function openChatStream(input, handlers) {const controller = new AbortController();fetch("/api/chat/stream", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(input),signal: controller.signal}).then(async (response) => {if (!response.ok) throw new Error("stream request failed");const reader = response.body.getReader();const decoder = new TextDecoder();let buffer = "";while (true) {const { value, done } = await reader.read();if (done) break;buffer += decoder.decode(value, { stream: true });const frames = buffer.split("\n\n");buffer = frames.pop() || "";for (const frame of frames) {const line = frame.split("\n").find((item) => item.startsWith("data:"));if (!line) continue;const payload = line.slice(5).trim();if (payload === "[DONE]") {handlers.onDone();return;}handlers.onDelta(JSON.parse(payload));}}handlers.onDone();}).catch((error) => {if (error.name !== "AbortError") handlers.onError(error);});return { abort: () => controller.abort() };}
For state updates, it is recommended to separate the “answer content” channel from the “reasoning process” channel. The reasoning process is displayed in a collapsible panel and does not interfere with reading the final answer by default. The answer content is appended incrementally; however, UI updates should be throttled or batched to avoid triggering a full component tree re-render for every individual character.
6. Rendering Pipeline and Rich Text Capabilities
Chat content often includes markdown text, code blocks, mathematical formulas, and charts. The rendering pipeline should execute in the order of “sanitize first, then parse, then enhance”:
- Escape the raw text and filter out dangerous tags.
- Parse the markdown structure.
- Apply syntax highlighting to code blocks and attach copy buttons.
- Render formulas and charts through controlled components.
All extended renderers should adopt a whitelist mechanism, forbidding inline script execution and untrusted links.
For code block copying, the browser Clipboard API can be used, with fallback to text selection if the API is unavailable. Formula rendering should be queued asynchronously to avoid blocking the main thread when long conversations contain many formulas. Chart rendering needs to listen for theme changes and container resize events, recalculating colors and layout when switching between light and dark modes. For incomplete code blocks or formulas in streaming output, the renderer should tolerate incomplete syntax by displaying plain text placeholders first, then enhancing the content once the fragment is complete.
7. Theming, Interaction, and Accessibility
The theme system is recommended to be implemented with CSS variables, abstracting background, text, borders, code highlighting colors, formula, and chart palettes uniformly. Switching between light and dark themes only changes root variables, and the user’s selection is persisted.
The interaction layer needs to cover: message scroll anchoring, auto-scroll with pause when the user scrolls up, a stop-streaming button, error retry, code copy feedback, and reasoning process collapse/expand.
For accessibility, buttons should have readable labels, and the streaming area should have an appropriate live-region announcement strategy to avoid frequently interrupting screen reader output.
8. State Management and Persistence
State management should distinguish between “transient state” and “persistent state.” Message lists, conversation lists, and user settings can be persisted. Streaming intermediate fragments, request controllers, and transient error notifications should not be written to persistent storage.
When persisting data, only necessary fields should be saved, and a version number along with migration functions should be included to prevent structural upgrades from making old data unusable. Sensitive information, such as API credentials, must not be written to frontend local storage. Such data should be handled by a server-side proxy with proper permission validation.
9. Performance Optimization and Engineering Practices
Performance optimization can be approached from four angles:
- Code splitting: Load rendering plugins such as formulas, charts, and code highlighting on demand.
- List optimization: Use virtual lists or pagination for long conversations.
- Render throttling: Merge streaming increments frame-by-frame before updating.
- Offloading heavy computations: Move expensive parsing work into Web Workers.
For engineering practices, it is recommended to write unit tests for the streaming parser, rendering pipeline, and state migrations. A unified specification should be established for error boundaries and fallback UI states.
10. Security, Compliance, and Deployment Extensions
On the security side, the frontend should never connect directly with model API keys. Requests should go through a server-side proxy that handles authentication, rate limiting, and auditing. Both user input and model output should be filtered as necessary. Markdown rendering must be protected against cross-site scripting (XSS). External link protocols should be restricted to a safe whitelist.
On the deployment side, frontend static assets can be placed in object storage and accelerated via a CDN. API services run on container platforms, paired with logging services and monitoring alerts to observe streaming failure rates, time-to-first-byte, and error distribution.
Potential extension directions include multi-model routing, tool calling, knowledge base retrieval, and conversation sharing. However, all of these should be integrated through the API adaptation layer and the rendering plugin mechanism, keeping the template core stable.
In summary, a high-quality web-based intelligent chat template is not just a collection of UI components. It is a systematic engineering effort involving streaming protocols, state orchestration, rendering safety, and engineering governance. By following the layered architecture and pipeline practices described above, developers can quickly build a maintainable, extensible, and deployable conversational application foundation without being locked into any specific vendor or implementation.
