Replicating a Chat Product with Open-Source LLMs: An Evaluation Framework and Engineering Checklist
This guide helps development teams build a conversational prototype with open-source large language models. It covers how to scope a replica of core chat features, a three-stage replication process, a structured intent parsing example, and checklists for functional fidelity, interaction consistency, response quality, and error handling. It also explains streaming output rendering and context management.
1. Scope and Replication Goals
This guide is for development teams that need to build a conversational prototype quickly. The replication target is the core experience of a chat product, including sending messages, multi-turn context, streaming output, and error notifications. It does not aim for pixel-perfect copying of a user interface, and it does not involve a competitor’s private APIs or data.
The conclusions come from a methodology description. They do not include measured rankings of any specific model. Readers should validate them with their own test sets and deployment environments. All thresholds in this guide are starting recommendations and should be adjusted to business requirements.
2. Three Stages of the Replication Process
Stage 1: Feature breakdown. Map the target product’s user paths as a flowchart, and mark the “skeleton” features that must be kept, such as the main chat flow, context management, and result rendering. Features such as theme switching and share links belong to the “flesh” category. Build them after the skeleton is stable.
Stage 2: Model selection. Choose several models that differ in parameter scale, architecture, and quantization method. Use the same test set to compare instruction following, long-text handling, and structured output. Record each model’s name, version number, parameter count, quantization format, and inference framework. Without version numbers, later results cannot be reproduced.
Stage 3: Front-end replication. Use component-based development. Store spacing, colors, border radius, and font sizes in CSS variables, and manage them in one place. On mobile, use the visual viewport as the reference so that the input box is not covered when the keyboard opens.
3. Semantic Layer: Parsing User Input into Structured Requests
The semantic layer converts natural language input into JSON that the backend can process. The example below uses an OpenAI-compatible API. The model name is read from an environment variable and should be replaced with the actual deployed model.
import jsonimport osfrom openai import OpenAIclient = OpenAI(base_url=os.environ["LLM_BASE_URL"],api_key=os.environ["LLM_API_KEY"],)MODEL = os.environ.get("LLM_MODEL", "your-model-name")ALLOWED_INTENTS = {"chat", "code_generation", "summarize"}SYSTEM_PROMPT = """你是一个指令解析器,只输出一个JSON对象,不输出任何其他文字。字段定义:- intent: 取值为 "chat"、"code_generation"、"summarize" 之一- params: 对象,可包含 language(字符串,如 "zh"、"ja")和 max_length(整数,未指定时为 null)- use_context: 布尔值,表示用户是否引用了上文示例输入:用日语总结上一段,不超过100字示例输出:{"intent": "summarize", "params": {"language": "ja", "max_length": 100}, "use_context": true}"""FALLBACK = {"intent": "chat", "params": {}, "use_context": False}def validate(obj: dict) -> bool:return (isinstance(obj, dict)and obj.get("intent") in ALLOWED_INTENTSand isinstance(obj.get("params"), dict)and isinstance(obj.get("use_context"), bool))def parse_intent(user_text: str, retries: int = 2) -> dict:for _ in range(retries + 1):resp = client.chat.completions.create(model=MODEL,temperature=0,max_tokens=256,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": user_text},],)raw = resp.choices[0].message.content.strip()try:obj = json.loads(raw)except json.JSONDecodeError:continueif validate(obj):return objreturn FALLBACK
The key settings in this code work as follows. Temperature is set to 0 to reduce output variation for the same input. max_tokens is capped at 256. That is enough for a short JSON object and prevents the model from producing long explanations. If parsing fails, the function retries up to two times. If it still fails, it falls back to regular chat so the front end does not show an error.
4. Multi-Dimensional Evaluation System and Checklists
Evaluation should cover both objective metrics and subjective experience. Each of the four dimensions below lists checks that can be carried out. The thresholds are starting points. Calibrate them after a trial run based on the sample results.
1. Functional Fidelity
| Check item | Steps | Suggested pass criteria |
|---|---|---|
| Multi-turn context reference | Send three consecutive messages. In the third, ask about key information from the first. | At least 95% correct references across 100 test cases |
| Empty and very long input | Send an empty string, and send a text of about 20,000 characters. | Empty input shows a prompt. Long input causes no error and shows a truncation notice. |
| Multi-condition instructions | Enter a combined instruction such as “Summarize only the second paragraph and output it in Japanese.” | At least 90% of cases satisfy every condition |
| Structured output | Run the parsing function from Section 3. | JSON validity of at least 98%, with correct fallback on failure |
2. Interaction Consistency
| Check item | What to check | Suggested standard |
|---|---|---|
| Input box size | Single-line height, maximum height, and the scroll trigger when content overflows | Deviation from the design spec no greater than 2px |
| Border radius and spacing | Corner radius, inner padding, and outer margin | All values are multiples of 4px or 8px |
| State transition animation | Transitions for button hover, press, and disabled states | Consistent transition duration, for example 150ms to 200ms |
| Mobile safe area | Bottom gesture bar and notch | Use env(safe-area-inset-bottom) to reserve space |
3. Response Quality and Efficiency
Response quality requires both human scoring and automated metrics. Randomly sample 100 test prompts. Two reviewers score each response independently on a scale of 1 to 5, and then the team calculates scoring consistency. If the consistency coefficient is below 0.6, revise the scoring guidelines before continuing.
Measure efficiency with timestamps. Record the time from sending the request to receiving the first token, and report the P50 and P95 values. Also record the overall generation speed in tokens per second. Run all measurements on the same hardware and at the same concurrency level. Otherwise, comparisons between models are meaningless. Quantized models usually run faster, but use the same test set to check whether coherence has dropped.
4. Error Handling Completeness
| Scenario | Action | Expected behavior |
|---|---|---|
| Network disconnection | Turn off the network during generation | Show a clear message and keep the user’s unsent draft |
| Rapid repeated clicks | Click the send button five times within one second | Send only one request, or process the requests in a queue |
| Switching sessions during generation | Switch to another session while streaming is still in progress | Cancel the old request. The new session does not show old content. |
| Service returns 503 | Simulate server unavailability | Retry with exponential backoff. If the final attempt fails, show a message asking the user to try again later. |
5. Key Engineering Points
Render streaming output incrementally, not character by character. Model services usually return data in chunks or tokens. The front end places incoming text in a buffer, then flushes the buffer to the DOM on a cycle of 16 to 33 ms. This keeps the output visually continuous without the stutter that comes from reflowing the page on every token. SSE and WebSocket can both carry streaming data. The choice depends on the server framework, and neither one is required.
let buffer = "";let scheduled = false;function onChunk(text) {buffer += text;if (!scheduled) {scheduled = true;setTimeout(() => {outputEl.textContent += buffer;buffer = "";scheduled = false;}, 24);}}
For context management, use a sliding window combined with summarization. Keep the most recent 10 turns in full. When the history exceeds 6,000 tokens or the conversation exceeds 20 turns, trigger a summarization task. This task compresses earlier history into key points of no more than 300 characters. If the summarization request fails, discard the oldest turns directly without blocking the current conversation. Adjust these values based on the model’s context window and your cost budget.
For a stable multi-platform style, store spacing, colors, and font sizes in CSS variables. Fine-tune the layout for mobile with media queries, and use rem units for sizes. Do not use 100vh for viewport height, because mobile browsers do not change it when the address bar or keyboard appears. Adjust the input box position based on resize events from window.visualViewport.
6. Common Issues and Solutions
Complex instructions are only partly executed. In a multi-condition request, the model may skip one of the conditions. During evaluation, ask the model to list its breakdown steps before giving the answer. This helps determine whether the error comes from misunderstanding the request or from failing to execute it. Production services generally should not expose this reasoning output, because it adds latency and token cost, and it can mix reasoning text into structured results. The parser should read only the final JSON.
The mobile keyboard covers the input box. This is the most common front-end issue. To reproduce it, open the input box on a real device and record the operating system, browser version, and keyboard height. To fix it, listen for changes in visualViewport, and set the bottom value of the input area to the viewport offset.
The model output contains abnormal characters. Control characters or unclosed Markdown markers can cause rendering lag or broken layout. Post-processing can remove invisible control characters and limit the length of each message. The cleaning function should only normalize formatting. It must not rewrite the meaning of the content.
7. Conclusion and Scope
The replication result depends on two factors: the model’s ability to understand instructions and generate responses, and the detailed implementation in the front end and engineering layers. No general answer exists for how much each factor contributes. To find out which one dominates, run two controlled experiments. The first experiment keeps the front end fixed and changes only the model. The second keeps the model fixed and adjusts only the front-end spacing, animation, and streaming render parameters. Compare how much the results change in each group to see where the bottleneck lies.
The checklists and thresholds in this guide are suitable as starting points for evaluation. Before formal acceptance, recalibrate them with samples of real user prompts. Record all test conditions, including model version, hardware, concurrency level, and review criteria. Without these records, results are hard to reproduce and difficult to use for comparison across teams.
