Replicating an AI Chat Web App with Multi-Agent Collaboration: Engineering Practices for Streaming, Security, and Validation
This article describes an engineering approach to replicating a conversational AI web app through multi-agent collaboration. It breaks requirements into session, message, settings, and error-handling modules; presents a frontend/backend proxy architecture; explains SSE-based streaming with cancellation and buffering details; covers API key security and configuration management; and proposes a two-round validation method that tests exception paths as well as the main flow. It also lists practical improvements for rendering, storage, Markdown safety, and regeneration versioning.
1. Background and Problem Definition
Conversational web applications generally share the same core form: a session list on the left, a message stream in the middle, an input box at the bottom, and replies rendered incrementally in a streaming manner. Such pages look simple, but in practice they involve state management, network fault tolerance, secure storage, and rendering performance.
A common mistake when replicating this type of product is to focus only on UI restoration and ignore edge cases in real interactions, such as recovery after a network interruption, scroll positioning for long text, cancellation of concurrent requests, and state isolation when the user switches sessions. This article therefore splits the goal into two layers: the first layer is functional completeness, enough to complete a normal conversation; the second layer is experience and robustness, providing reasonable feedback under abnormal conditions.
2. Requirements Breakdown and Product Feature Structure
Before writing code, requirements should be written into a structured product document. An executable document usually contains the following modules.
- Session management: create, switch, rename, and delete sessions, and persist history.
- Message interaction: send text messages, display user messages and model replies, and support copy and regenerate.
- Streaming output: render reply content incrementally and provide an entry point to stop generation.
- Settings panel: configure service address, model name, system prompt, and other parameters; sensitive configuration is stored only on the server.
- Exception handling: provide clear prompts for request failures, timeouts, and insufficient quota, while preserving the content the user has already entered.
The feature structure can be represented as a tree diagram to help development and testing align on scope:
Chat application├── Session module│ ├── Create / switch / delete│ └── History persistence├── Message module│ ├── Send and render│ ├── Streaming incremental output│ └── Stop / regenerate├── Settings module│ └── Model parameters (stored on the server)└── Exception module├── Network error retry└── User-facing prompts
The document should also state acceptance criteria for each feature. For example, “After generation is stopped, the interface stops appending text within one second, and content already received remains in the message.” Quantifiable conditions like this are easier to test than vague statements such as “smooth experience.”
3. Overall Architecture Design
A frontend/backend separation structure is recommended. The frontend handles the interface and state, and the backend proxy handles authentication, parameter validation, and request forwarding. This brings two direct benefits: first, keys exist only in server environment variables or a secret management service and are not exposed to the browser; second, the backend can uniformly handle rate limiting, logging, and error formats, making frontend logic simpler.
Browser│ POST /api/chat (SSE stream)▼Backend proxy│ Validate parameters, attach auth headers▼Upstream model service
The backend should follow the principle of least privilege. The proxy endpoint should accept only whitelisted parameter fields, ignore unknown fields, and set upper limits on message length and the number of history turns to prevent abnormal requests from amplifying cost.
4. Core Implementation of Streaming Output
Streaming output is a key experience in conversational pages. Implementations usually use Server-Sent Events (SSE) or chunked transfer, with the frontend reading the response body segment by segment and appending it to the current message.
The following is illustrative frontend code for reading the stream, with UI rendering details omitted:
async function streamChat(messages, onDelta, signal) {const res = await fetch('/api/chat', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ messages }),signal,});if (!res.ok) throw new Error(`Request failed: ${res.status}`);const reader = res.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();for (const line of lines) {if (!line.startsWith('data: ')) continue;const payload = line.slice(6).trim();if (payload === '[DONE]') return;onDelta(JSON.parse(payload).delta);}}}
Three points require attention in the implementation. First, use stream: true during decoding; otherwise multibyte characters split across chunks will be truncated, especially for Chinese. Second, line buffering must retain the incomplete last line; otherwise data will be lost. Third, stopping generation relies on AbortController; after calling abort(), both the read loop and the UI state should be cleaned up.
5. Key Security and Configuration Management
API keys are one of the most error-prone parts of this type of project. Common problems include writing keys into frontend code, committing them to a version repository, or printing complete request headers in logs. The correct approach is as follows:
- Inject keys into the backend process only through environment variables or a secret management service.
- Mask authentication fields in backend logs, retaining only the last four digits for troubleshooting.
- If the frontend settings panel needs to display configuration status, return only “configured” or “not configured” and do not echo key content.
- Rotate keys regularly and check whether old keys have become invalid after changes.
During the validation phase, you can first use a test key with restricted permissions to complete the full flow, confirm that functionality works, and then switch to the production environment.
6. Two-Round Validation Method
A complete development cycle often includes two rounds of interaction. The first round provides the requirements document and asks for the product structure and a runnable page. The second round adds real service configuration and asks for validation in an environment with dependencies. The difference between the two rounds is mainly the depth of testing.
The output of the first round can usually complete the main flow, but it easily misses exception paths. If the second round only performs a smoke test of “send a message and see a reply,” it will hide many problems. More reliable validation should cover the following scenarios:
- When the network is interrupted, does the interface show an error and preserve the input content?
- When two messages are sent quickly in succession, are replies displayed serially without overwriting each other?
- When switching sessions, is the content being generated correctly canceled or attributed to the original session?
- With long replies, does automatic scrolling stop following after the user manually scrolls up?
- After refreshing the page, is the historical session fully restored?
Test results should be recorded as a defect list, with each item containing reproduction steps, expected behavior, actual behavior, and priority. This allows subsequent iterations to close items one by one instead of repeatedly relying on subjective judgment.
7. Improvement Suggestions
Based on the practices above, the following improvements have a noticeable impact on experience.
- Add throttling to streaming rendering, for example updating the DOM at most once per frame, to avoid page stuttering during long replies.
- Store session data locally with an index structure, and load it in pages after a certain number of records.
- Apply security filtering to Markdown and code blocks to prevent script content in model output from being executed directly.
- Keep version numbers of original replies for regeneration, allowing users to switch between and compare multiple results.
These improvements are general engineering measures, and their costs should be evaluated against the team’s technology stack and operational conditions before implementation.
8. Conclusion
The key to replicating a conversational web page is not pixel-perfect UI restoration, but writing requirements clearly, defining architecture boundaries correctly, implementing streaming and security details solidly, and validating results with tests that cover exception paths. Following the order of “structured requirements, layered architecture, cancellable streaming, server-side key storage, and staged testing,” a clear and maintainable prototype can be obtained within a relatively short cycle.
