LLM-Assisted Conversational Web App Development: From Requirements Breakdown to Iterative Optimization

    This article explains how to plan and build a conversational web application with LLM assistance, covering requirements breakdown, a feature document and structure diagram, frontend/backend responsibilities, streaming rendering, context management, security and key handling, staged testing, UX improvements, and common pitfalls. It focuses on the engineering details that are often missed when asking a model to "write a chat page" directly.

    1. Problem Definition: Why Conversational Apps Need Requirements Breakdown First

    A conversational web app may look like just an input box and a message list, but in practice it involves multiple subsystems: multi-turn context management, streaming response rendering, file and long-text input, voice interaction, error and rate-limit handling, and more. If you simply ask a development tool or an LLM to “write a chat page,” the result often runs but lacks critical pieces: conversations disappear after a page refresh, long replies lag, API keys are exposed in the frontend, and the UI gives no feedback when something fails.

    Before implementation, you should break the goal into verifiable feature points. The approach in this article has three steps: first, produce a product feature document and structure diagram to define the scope; second, implement a minimum viable version; third, after runtime credentials are available, test in a real environment and optimize the experience based on the test results.

    2. Product Feature Document and Structure Diagram

    The feature document should include at least the following: a feature list, the input and output of each feature, failure scenarios, priorities, and acceptance criteria. Below is an example feature structure for a conversational app:

    1. Conversational App
    2. ├── Session Layer
    3. │ ├── Create new session
    4. │ ├── Historical session list (search, rename, delete)
    5. │ └── Session persistence (local storage or server-side storage)
    6. ├── Input Layer
    7. │ ├── Text input (line breaks, quick send)
    8. │ ├── File input (type and size validation)
    9. │ └── Voice input (record, transcribe, edit, then send)
    10. ├── Inference and Output Layer
    11. │ ├── Streaming output (character-by-character or chunk-by-chunk rendering)
    12. │ ├── Deep thinking process display (collapsible)
    13. │ ├── Web search result citations
    14. │ └── Stop generation, regenerate
    15. ├── Output Presentation Layer
    16. │ ├── Markdown rendering
    17. │ ├── Code block highlighting and one-click copy
    18. │ └── Voice playback (text-to-speech)
    19. └── System Layer
    20. ├── Authentication and key management
    21. ├── Rate limiting and quota notices
    22. └── Error handling and retry

    The “acceptance criteria” section is especially important. For example, “streaming output first-token latency is perceptible” is too vague. It should be rewritten as “after the request is sent, the UI displays content as soon as the first data chunk arrives and does not block the input field.” Such criteria can be converted directly into test cases.

    3. Architecture Selection and Responsibility Separation

    Conversational apps usually use a frontend/backend separation. The frontend handles UI state, message rendering, and user interaction. The backend stores keys, forwards requests, unifies error formats, and performs rate limiting and logging when necessary.

    On the frontend, you can choose a mainstream component-based framework. State management can be split by data type: conversation list, current conversation messages, input draft, and request state. This avoids putting everything into a single global object.

    On the backend, the most important principle is that keys must not be sent to the browser. The frontend calls only its own server-side API, and the server uses keys from environment variables to access the upstream model service. This is discussed further in Section 5.

    1. Browser ──► Application server (auth, rate limiting, logging) ──► Upstream model service
    2. ▲ │
    3. └──────────── Streaming data chunks (SSE or chunked transfer) ◄────┘

    4. Core Implementation Points

    4.1 Multi-Turn Context Management

    The model itself does not retain conversation state. Every request needs to carry the necessary historical messages. In production engineering, two problems must be solved: truncation strategy when history is too long, and maintaining the order of messages from different roles.

    A common approach is to keep the most recent complete turns and summarize earlier content. When truncating, prioritize system instructions and the most recent user question so that the model does not “forget” the user’s core constraints after truncation.

    4.2 Streaming Output Rendering

    Streaming output significantly reduces the user’s perceived waiting time. When implementing it, pay attention to three points: parse data chunk by chunk and avoid rendering incomplete Markdown syntax directly; support user-initiated stop and correctly release the connection; and when the network is interrupted, keep already received content and prompt for retry.

    Below is an example of reading chunked data with fetch. The API path is illustrative:

    1. async function streamChat(messages, onChunk, signal) {
    2. const response = await fetch('/api/chat', {
    3. method: 'POST',
    4. headers: { 'Content-Type': 'application/json' },
    5. body: JSON.stringify({ messages }),
    6. signal,
    7. });
    8. if (!response.ok) {
    9. throw new Error(`Request failed with status ${response.status}`);
    10. }
    11. const reader = response.body.getReader();
    12. const decoder = new TextDecoder('utf-8');
    13. let buffer = '';
    14. while (true) {
    15. const { value, done } = await reader.read();
    16. if (done) break;
    17. buffer += decoder.decode(value, { stream: true });
    18. onChunk(buffer);
    19. }
    20. }

    The example uses the stream option of TextDecoder to correctly handle multi-byte characters that are split across chunks. If this option is omitted, Chinese characters may be garbled at chunk boundaries.

    4.3 Markdown and Code Blocks

    Model replies often contain headings, lists, tables, and code blocks. Use a mature Markdown parsing library for rendering and sanitize the output to prevent script injection. Code blocks should support language labels, horizontal scrolling, and one-click copy. During streaming, an unclosed code fence can cause all subsequent text to be mistaken for code. Therefore, you can check the number of fences before rendering and temporarily close unclosed fences.

    4.4 File and Long-Text Input

    File input requires type and size validation on the frontend, and validation again on the server because frontend validation can be bypassed. After upload, show progress and failure reasons. For very long text, display the character count in the input box and give a clear warning before submission, rather than waiting for the server to return an incomprehensible error.

    4.5 Voice Input and Playback

    Voice capabilities are usually split into two parts: speech-to-text for input and text-to-speech for playback. Both depend on browser microphone permissions or upstream services. When implementing them, handle the following cases: the user denies permission, the recording is too short, the recognition result is empty, and the user continues typing during playback. Playback should provide a stop button and stay synchronized with the text content.

    5. Security and Key Management

    Access credentials are sensitive information and should follow three basic rules:

    1. Keys should exist only in server-side environment variables or a secrets management service. They should not be committed to the code repository or appear in frontend build artifacts.
    2. Server logs should not record full request bodies or keys. Log only request IDs, latency, and status codes.
    3. Public endpoints should enforce authentication and rate limiting to prevent abuse and unexpected costs.

    During testing, if a key must be provided temporarily, inject it through environment variables and rotate it promptly after testing.

    6. Staged Testing: First Make It Work, Then Verify It

    In practice, you can divide development into two prompt rounds. In the first round, provide only the requirements and let the system generate the document, structure, and initial implementation. In the second round, after real runtime conditions are available, provide the key and let the system verify functionality in a real environment.

    The difference between the two rounds is test depth. If the second round only performs a smoke test such as “send one message and receive a reply,” it is easy to miss the following issues:

    • Whether context is correct after multiple consecutive turns;
    • Whether the connection is actually closed after stopping generation;
    • Whether the UI remains stuck in a loading state when the network is interrupted;
    • Whether overly long input returns an understandable error;
    • Whether rapid repeated clicks on send produce duplicate requests.

    Therefore, the acceptance checklist should be defined in the first round. In the second round, verify each item against the checklist and record the result and reproduction steps. This avoids the misjudgment that “it looks like it works.”

    7. UX Optimization Suggestions

    After the basic functionality is complete, you can improve the experience in the following areas:

    • Specific error messages: Distinguish network errors, authentication failures, insufficient quota, and content that is too long, and give handling advice for each.
    • Retry and recovery: Keep failed messages in the input box so users can resend with one click without retyping.
    • Session recovery: After a page refresh, restore the draft and message list of the most recent session.
    • Accessibility support: Provide readable labels for buttons and ensure keyboard users can send, stop, and switch sessions.
    • Responsive layout: On narrow screens, collapse the historical session list by default and prioritize a readable width for the message area.

    These optimizations do not require changing the core architecture, but they can significantly reduce user effort.

    8. Common Pitfalls

    First, making the UI look like a mature product while ignoring failure paths. The design of failure paths often determines users’ trust in the product.

    Second, introducing complex features too early. If streaming output and session management in the minimum version are not yet stable, there is no need to rush into multi-user collaboration or plugin mechanisms.

    Third, using model output as a substitute for acceptance. Generated code needs to be run, tested, and reviewed, especially security-related parts such as key handling, input validation, and permission checks.

    Fourth, ignoring cost and quota. Even at the prototype stage, set server-side call limits and alerts to prevent test loops from running out of control.

    9. Conclusion

    The difficulty of developing a conversational web app is not the interface itself, but requirements boundaries, streaming data handling, key security, and validation in a real environment. Produce the feature document and structure diagram first, then divide frontend and backend responsibilities, and use a checklist to drive testing. This can significantly reduce rework. After runtime conditions are available, developers should prioritize failure paths and edge cases before adding visual and interaction enhancements.