Building a Conversational Web Page with an AI Agent: A Practical Guide

    This guide explains how to use an AI agent to build a conversational web page for large language models. It covers three stages: defining product features, reproducing the interface and interaction behavior, and optimizing the user experience. It also covers two-round prompt design, a general streaming API integration example that keeps the key on the server, acceptance checklists, and risks including cost, content safety, third-party dependencies, and reliability.

    1. Background and Goals

    A conversational web page is the most common way to deliver a large language model. Users type a question, the page returns the answer token by token in a streaming fashion, and the session keeps a multi-turn history. This kind of product looks simple, but it includes several modules: session management, message rendering, error handling, and API key security.

    An AI agent can split development into three tasks: defining product features, reproducing the existing interaction design, and optimizing the experience based on practical experience. Each task has a different goal and different acceptance criteria. A product document requires clear feature boundaries. Reproduction requires the interface and interaction behavior to match the reference. Optimization requires a better experience without breaking existing features.

    This article focuses on general methods and does not depend on any specific model or tool. Readers can apply the prompt structures, checklists, and code snippets to their own tech stack.

    2. Stage 1: Product Feature Definition

    Before coding, ask the AI agent to produce a product report. The report should include at least the following:

    • Core features: create a new session, send messages, streaming output, stop generation, regenerate, session history list, rename and delete sessions.
    • Auxiliary features: Markdown rendering, code block highlighting and copying, file or image upload, dark mode, mobile adaptation.
    • Account and settings: login status, model or parameter selection, personalization settings.
    • Edge cases: empty input, overly long input, network interruption, API rate limiting, server errors.

    The feature structure can be shown as a tree list, so each item can be checked during development:

    1. Chat web page
    2. ├── Session management
    3. │ ├── New session
    4. │ ├── History list (grouped by time)
    5. │ └── Rename / Delete / Share
    6. ├── Chat area
    7. │ ├── Message input (multi-line, keyboard shortcut to send)
    8. │ ├── Streaming output and stop generation
    9. │ └── Message actions (copy, regenerate)
    10. ├── Content rendering
    11. │ ├── Markdown and code highlighting
    12. │ └── Formulas and tables
    13. └── Settings
    14. ├── Theme switching
    15. └── Parameter configuration

    The value of the product report is that it fixes the requirement boundaries. When disagreements come up during development, the team can refer back to the report.

    3. Two-Round Prompt Design

    In practice, prompts are usually given in two rounds. The two rounds have different responsibilities, so they should not be mixed.

    Round 1: Requirement input. This round states the role, goal, deliverables, and constraints. For example:

    1. Role: senior product manager and front-end engineer.
    2. Deliverables: product feature document, feature structure diagram, runnable front-end page, optimization notes.
    3. Constraints: do not introduce unnecessary dependencies. Read all external addresses from configuration.
    4. Scope: complete the core conversation flow first, then handle auxiliary features.

    Round 2: Runtime conditions and verification. This round provides runtime parameters such as the API address and model name, and explicitly asks the AI agent to verify the result. Keys should be provided through environment variables, not written into code or front-end resources. After receiving this round, an AI agent often runs only one successful request, while some proactively cover error scenarios. The difference strongly affects final quality, so round 2 should list a verification checklist instead of a single line such as “test it”.

    When the same prompt goes to different AI agents, the depth of final verification often differs. Acceptance should not rely entirely on the agent’s self-assessment. Keep both manual review and automated testing.

    4. General Implementation of API Integration

    A front end that holds the key directly carries a leak risk, so chat requests should pass through your own back-end relay. The example below shows general streaming request handling. The API URL and model name are placeholders.

    1. import os
    2. import json
    3. import requests
    4. API_URL = os.environ["LLM_API_URL"] # Read from environment variables, not hardcoded
    5. API_KEY = os.environ["LLM_API_KEY"] # The key is stored only on the server
    6. def stream_chat(messages, model_name):
    7. headers = {
    8. "Authorization": f"Bearer {API_KEY}",
    9. "Content-Type": "application/json",
    10. }
    11. payload = {
    12. "model": model_name,
    13. "messages": messages,
    14. "stream": True,
    15. }
    16. with requests.post(API_URL, headers=headers, json=payload,
    17. stream=True, timeout=60) as resp:
    18. resp.raise_for_status()
    19. for line in resp.iter_lines():
    20. if not line:
    21. continue
    22. text = line.decode("utf-8")
    23. if text.startswith("data: "):
    24. data = text[len("data: "):]
    25. if data == "[DONE]":
    26. break
    27. chunk = json.loads(data)
    28. delta = chunk["choices"][0]["delta"].get("content", "")
    29. if delta:
    30. yield delta

    This code has three key points. First, the key exists only in server-side environment variables. Second, streaming reads let the front end render content as it arrives. Third, a timeout is set so connections do not hang for a long time.

    Before going live, add the following: a maximum retry count for failed requests, input length validation, and unified mapping of upstream error codes.

    5. Interface Reproduction Essentials

    When reproducing the interface, the goal is to make users feel familiar with it, not to copy a third-party page pixel by pixel. Directly copying others’ icons, illustrations, font files, and copy carries copyright risk and can cause confusion. A safer approach is to follow common conversational interaction patterns and design the visual solution independently.

    The work can be broken down into the following layers:

    • Layout structure: session list on the left, main chat area on the right, fixed input box at the bottom.
    • Sizes and spacing: use design tokens (colors, font sizes, corner radii, spacing) consistently so they are easy to adjust later.
    • Responsive adaptation: on narrow screens, the sidebar collapses into a drawer, and the input box stays visible when the soft keyboard appears.
    • Status feedback: sending, generating, stopped, and error states each need a clear visual indicator.

    After reproduction, compare each item against the product report, and record deviations with their causes.

    6. Experience Optimization Directions

    Based on the reproduction, you can make targeted improvements. The following directions are common in conversational applications:

    1. Input experience: support multi-line input, and let users choose between Enter to send and Shift+Enter for a new line. During IME composition, avoid sending by mistake.
    2. Long content handling: use virtual scrolling for long sessions to avoid page lag, and load history messages on demand.
    3. Reliability: keep the draft when the network drops. When the connection recovers, continue generation or retry.
    4. Accessibility: add labels to icon buttons so that all actions can be completed with a keyboard.
    5. Export and sharing: support exporting sessions as Markdown files. Share links need to account for privacy scope and expiration time.
    6. Themes and personalization: provide light, dark, and follow-system modes.

    Each optimization should correspond to a verifiable result. For example, “smooth scrolling in long sessions” can be tested with a session that contains one thousand messages.

    7. Acceptance Checklist

    Acceptance should cover three areas: functionality, compatibility, and security.

    Functional acceptance

    • Creating, sending, stopping, regenerating, and deleting sessions all complete normally.
    • Refreshing the page during streaming output does not lose message history.
    • Markdown, code blocks, and tables render correctly, and code copying works.

    Compatibility acceptance

    • Mainstream desktop and mobile browsers work normally.
    • On narrow screens, the input box position and size meet expectations and the soft keyboard does not cover it.

    Security acceptance

    • The front-end resources and source code contain no keys.
    • User input is length-limited, and rendered content is escaped to prevent script injection.
    • Logs do not record complete private user content.

    8. Risks and Considerations

    Cost risk. Streaming conversations are billed by usage. Set a maximum output length per request, and limit how often each user can make calls.

    Content safety risk. Model output may be inaccurate or inappropriate. Public-facing products need content moderation, and the interface should remind users to verify important information independently.

    Dependency risk. Parameters, rate limits, and response formats of third-party APIs may change. Encapsulate API calls in a separate module so they are easier to replace and regression-test.

    Result reliability risk. Code generated by an AI agent may cover only the main path. Before merging, perform human code review and automated testing. Do not treat the agent’s self-report as the only basis.

    9. Conclusion

    Building a conversational web page with an AI agent depends on writing requirements clearly and completing verification thoroughly. Round 1 prompts define the feature boundaries, and round 2 prompts define runtime conditions and verification depth. The product report, interface reproduction, and experience optimization each have their own acceptance criteria, and all three are necessary.

    Following this structure, a team can get a runnable, verifiable, and continuously iterable conversational web prototype in a relatively short time. Future work can extend to observability, permission systems, and evaluation systems.