A Practical Guide to AI-Assisted Development for Conversational Web Applications
This guide explores how to leverage AI-assisted development tools to build conversational web applications from requirements to delivery. It covers creating executable requirement documents, designing a secure technical architecture (focusing on key management, streaming output, and context control), and establishing a two-round prompting and testing workflow to ensure a deliverable and maintainable product.
1. Background and Objectives
The core layout of conversational web applications is quite stable: a session list on the left, a message stream on the right, an input box at the bottom, and model replies presented word-by-word in a streaming manner. The frontend interactions of such products are not complex, but doing it well requires simultaneously handling the network layer, state management, security boundaries, and experience details.
The emergence of AI-assisted development tools makes it possible to “go directly from a requirement description to a runnable product.” However, whether the generated code can be used directly depends on the clarity of the input requirements and the sufficiency of post-delivery validation. This article uses “replicating a conversational web application” as a practice object to outline a complete methodology from requirements to delivery, with three main goals:
- Form a product feature document and structure diagram that can be handed over to development tools or teams for execution;
- Clarify the technical architecture, especially the three error-prone areas: key management, streaming output, and context control;
- Establish a phased prompting and testing workflow to avoid stopping just because the interface “runs.”
It should be noted that this article discusses general technical methodologies. It does not involve performance data of any specific model, nor does it rely on proprietary APIs of any specific platform.
2. Requirement Document: From Feature List to Structure Diagram
2.1 Core Features
An executable requirement document should first answer “what the user wants to accomplish” and then “how the system supports it.” The core features of a conversational web application can be summarized into the following five groups:
- Session Management: Create a new session, switch sessions, rename, delete, and display history grouped by time.
- Message Interaction: Users input text, and the system returns a reply in a streaming manner; supports stopping generation midway and regenerating the last reply.
- Content Rendering: Supports Markdown format, including headings, lists, tables, and code blocks; code blocks must provide a copy button.
- Parameter Configuration: Allows users to set system prompts, reply length limits, temperature, and other general parameters, and save them as personal preferences.
- Account and Keys: Users can fill in the API key in the settings. The key is only used for local or server-side request forwarding and is not displayed in plaintext on the page.
When writing requirements, each feature should be accompanied by “trigger conditions” and “expected results.” For example, “After clicking the stop button, the received content remains on the interface, and the unreceived part stops requesting.” Such descriptions can be directly translated into test cases.
2.2 Non-functional Requirements
Non-functional requirements are often ignored but determine whether the product can be used long-term. It is recommended to clarify at least the following metrics:
- First-token Response Time: The time from sending to the appearance of the first token on the interface should be recorded separately as a core experience metric;
- Error Recovery: Situations like network interruption, API timeout, and insufficient quota need clear prompt text and a retry entry point;
- Data Storage: Whether session data is stored in browser local storage or a server-side database must be specified in the document, along with the cleanup strategy;
- Compatibility: Covers mainstream desktop browsers and mobile widths, ensuring the input box and message list are usable on small screens;
- Accessibility: The keyboard can complete main operations like sending and switching sessions, and icon buttons are equipped with readable text labels.
2.3 Functional Structure Diagram
The following structure diagram can serve as a starting point for module division:
Conversational Web App├── Session Sidebar│ ├── New Session│ ├── Session List (grouped by date)│ └── Search and Delete├── Main Conversation Area│ ├── Message List (User Message / Model Reply)│ ├── Streaming Rendering and Stop Button│ └── Input Area (multi-line input, quick send)├── Settings Panel│ ├── System Prompt│ ├── Generation Parameters (length limit, temperature)│ └── API Configuration (address, key, model name)└── Common Capabilities├── Error Prompt and Retry├── Markdown Rendering and Code Highlighting└── Local Storage Read/Write
The value of the structure diagram is that it gives each module a clear boundary. During development, you can first complete the “message list” and “API request” separately, then assemble them into a complete page to reduce rework.
3. Technical Architecture Design
3.1 Frontend-Backend Division
Conversational applications usually adopt a “frontend interface + server-side forwarding” structure. The browser directly requesting the model API seems simple, but it exposes the API key and makes it difficult to uniformly handle rate limiting, logging, and error codes. The recommended division of labor is as follows:
- The frontend is responsible for interface rendering, input validation, session state, and streaming content display;
- The server is responsible for storing keys, forwarding requests, unifying error formats, and recording necessary audit logs;
- The model API is only accessed by the server, and the browser does not touch the original keys.
This structure also facilitates replacing the underlying model service. As long as the server provides a unified request and response format to the outside, the frontend does not need to be modified.
3.2 Secure Key Management
The key is the most critical asset to protect in this project. The following practices should be default requirements:
- Keys are injected through environment variables or a key management service, and are not written into the source code or version control;
- The server desensitizes keys in logs, keeping only the last few digits for troubleshooting;
- The frontend only saves the user’s own session content and does not cache server-side keys;
- Add access control to the server API to prevent unauthorized users from consuming quotas.
Below is a schematic server-side forwarding approach using generic placeholders. In actual deployment, replace them with the target service’s address and parameters:
// Example code: Server-side forwarding of chat requests (streaming)import express from "express";const app = express();app.use(express.json({ limit: "1mb" }));const API_BASE = process.env.LLM_API_BASE_URL; // Model service addressconst API_KEY = process.env.LLM_API_KEY; // Read only from environment variablesapp.post("/api/chat", async (req, res) => {const { messages, maxTokens = 1024 } = req.body;// Basic validation: message array cannot be empty, length must be limitedif (!Array.isArray(messages) || messages.length === 0 || messages.length > 200) {return res.status(400).json({ error: "Invalid message format" });}const upstream = await fetch(`${API_BASE}/chat/completions`, {method: "POST",headers: {"Content-Type": "application/json",Authorization: `Bearer ${API_KEY}`,},body: JSON.stringify({ messages, max_tokens: maxTokens, stream: true }),});if (!upstream.ok) {return res.status(502).json({ error: "Upstream service temporarily unavailable" });}res.setHeader("Content-Type", "text/event-stream");res.setHeader("Cache-Control", "no-cache");// Forward the upstream data stream to the browser chunk by chunkfor await (const chunk of upstream.body) {res.write(chunk);}res.end();});app.listen(3000);
Three points in the code are worth noting: the key only comes from environment variables; the input has basic validation to avoid oversized requests; upstream errors are converted into a unified error response, without exposing original error details to the frontend.
3.3 Streaming Output Implementation
Streaming output determines the “first-token response” experience. The frontend needs to do three things: read data chunk by chunk, incrementally update the interface, and support interruption.
// Example code: Frontend reads streaming response and supports interruptionasync function streamReply(messages, onChunk, signal) {const resp = await fetch("/api/chat", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ messages }),signal, // AbortController signal, used to stop generation});const reader = resp.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 });// Split by event boundaries, parse, and hand over to the interface for updatingconst parts = buffer.split("\n\n");buffer = parts.pop();for (const part of parts) onChunk(part);}}
There are three common types of issues during implementation:
- Buffering and event boundary mismatch: Data chunk boundaries do not align with event boundaries, requiring an incomplete buffer to be retained as shown above;
- Duplicate rendering: Redrawing the entire message list every time a chunk is received will cause noticeable lag in long conversations. You should only update the node of the current reply;
- Post-stop state: After the user interrupts, the interface should retain the received content and mark the reply as “incomplete” to avoid incomplete content appearing in the next context turn.
3.4 Session and Context Management
The model’s context length is limited, so long conversations must be truncated or summarized. Common strategies include:
- Sliding Window: Retain the most recent few rounds of messages and discard earlier content. Easy to implement, but may lose early key constraints;
- Fixed Retention: Always retain the system prompt and explicitly marked important messages, and crop the rest by window;
- Summary Compression: When history exceeds a threshold, the server calls the model to generate a summary, replacing early messages with the summary. Better effect, but increases cost and latency.
This project recommends first adopting a combination of “fixed retention + sliding window.” It does not require additional model calls, the behavior is predictable, and it is easy to test.
4. Two-Round Prompting Methodology
In AI-assisted development, prompting is not a one-time input, but a phased process. This article recommends a two-round prompting approach.
4.1 Round One: Requirements and Architecture Prompt
The goal of the first round is to have the tool produce a complete, runnable version. The prompt content should include:
- Role and Background: Explain the type of product to be built and the target users;
- Feature Scope: List the feature checklist and priorities from Chapter 2;
- Technical Constraints: Specify the frontend and backend tech stack, directory structure, and code standards;
- Deliverables: Require output of the feature document, structure diagram, source code, and run instructions;
- Acceptance Criteria: Provide checkable items, such as “The stop button can interrupt streaming output.”
The more specific the first-round prompt, the fewer subsequent modifications. Conversely, if you only write “make a similar chat web page,” the generated result often lacks error handling, mobile adaptation, and security measures.
4.2 Round Two: Key Configuration and Joint Debugging
After the first round is complete, enter the second round: provide the API key and service address to let the system actually call the model and verify the results. This step is easily simplified to “if it can reply, it passes,” but real validation should cover the following:
- Normal Conversation: Send multiple rounds of messages to check if the context is coherent;
- Exception Paths: Enter a wrong key, disconnect the network, send overly long text, and check if the prompts are accurate;
- Interruption and Retry: Click stop during generation, then regenerate, and check if the state is correct;
- Boundary Inputs: Empty messages, pure symbols, multi-segment code, special characters, and check if rendering and escaping are safe;
- Concurrency and Switching: When quickly switching sessions, replies from old requests should not be written into the new session.
In practice, different tools perform very differently in the second round. Some only do smoke testing—confirming the page can open and send a message; others proactively design the above use cases, find issues like missing escaping, session crosstalk, and duplicate submission on retry, and provide fixes. Therefore, the second-round prompt is best to explicitly state the test scope, rather than just providing the key.
4.3 Prompt Template Example
Below is a structural schematic of the second-round prompt, which can be adjusted according to the project:
Please use the provided API configuration to complete the following validation:1. Execute at least three rounds of multi-turn conversation to confirm the context is maintained correctly;2. Test three exceptions: wrong key, network disconnection, and oversized input, respectively, and record the prompt text;3. Verify the interface state and session data after stopping generation;4. Check if there is a script injection risk in Markdown rendering;5. Output a test report listing discovered issues and fixed items.
This phrasing turns “validation” into a task that can be checked item by item, making it easier for manual review.
5. Testing and Acceptance Checklist
During the acceptance phase, it is recommended to check by layers, rather than just looking at the interface.
Functional Layer: Are the creation, switching, and deletion of sessions correct? Are settings persistent? Is the data still there after refreshing the page?
Interaction Layer: Is the behavior of the send button consistent with the Enter key? Does Enter accidentally send during IME composition? Do long messages auto-scroll to the bottom, and does auto-scroll stop when the user scrolls up?
Security Layer: Do keys appear in frontend source code, network requests, and logs? Are user input and model output escaped or safely rendered? Are request body size and call frequency restricted?
Performance Layer: Is the first-token response time acceptable? Is scrolling and input smooth during long conversations (e.g., hundreds of messages)? Does memory usage continue to rise as the session grows?
Exception Layer: Do all types of errors have clear prompts? Can it retry after a timeout? Are server errors uniformly converted?
Upon completing each layer, record issues and conclusions. The value of an acceptance report is to provide a basis for subsequent iterations.
6. UX Improvement Suggestions
After completing the basic features, you can make the following improvements around real usage scenarios:
- Input Experience: Support multi-line input, give clear format limits when pasting images or files, and retain drafts after sending.
- Reply Experience: Long replies can be collapsed, code blocks support line numbers and language identifiers, and copy operations provide success feedback.
- Session Organization: Support session pinning, tags, and full-text search, with search results highlighting keywords.
- Error Feedback: Distinguish between situations like “invalid key,” “insufficient quota,” “service busy,” and “network exception,” and provide different handling suggestions.
- Accessibility: Add labels to icon buttons, ensure contrast meets standards, and support keyboard navigation.
The priority of improvement items should be determined by the target users. For developer-facing tools, prioritize code rendering and copying; for general user-facing products, prioritize simplifying settings.
7. Common Risks and Mitigation
Key Leakage is the most severe risk. Mitigation methods include server-side hosting, regular rotation, and setting usage alerts.
Injection Attacks come from two directions: user input may contain malicious scripts, and model output may also contain executable markup. Purification must be done before rendering and cannot be written directly to the page.
Cost Overrun usually stems from long conversations and unlimited generation length. You should set a maximum output per request, a daily call limit per user, and display the approximate scale of the current session on the interface.
Data Loss mostly occurs when browser local storage is cleared. If the product needs to save sessions long-term, it should provide an export function or introduce server-side storage.
Behavioral Deviation refers to the model or tool-generated code being inconsistent with requirements. The solution is to keep the requirement document as the sole basis and review against the acceptance checklist after each modification.
8. Conclusion
Replicating a conversational web application seems like interface work, but it actually involves requirement breakdown, security architecture, streaming data processing, and systematic testing. The following points can serve as general experience:
- The requirement document should be detailed to the point where it can be directly translated into test cases;
- Keys should only be kept on the server side, and the frontend should only handle display and interaction;
- Streaming output requires simultaneously handling data boundaries, incremental interface updates, and interruption states;
- Long context requires a clear truncation strategy;
- Use a two-round prompting approach: generate in the first round, validate in the second round, and clearly specify the test scope in the second round.
By following this methodology, regardless of the development tool used, you can turn “generated code” into a deliverable and maintainable product.
