Building a Conversational App on LLM APIs: Architecture, Streaming, Context Management, and Plugin Execution
This article outlines a practical path for rebuilding a basic conversational application on top of LLM APIs. It breaks down multi-turn session management, context trimming, streaming output, history import, tool calling, and natural-language plugin generation; presents a five-layer reference architecture; and provides illustrative data models and code for context assembly, cancellation-aware streaming, and message normalization. It also covers engineering controls for generated plugins, cost and quality evaluation, security and compliance, and a launch checklist.
1. Background and Problem Definition
Conversational applications have become a standard entry point for many products. Internal knowledge Q&A, customer support assistants, coding assistants, teaching companions, and similar scenarios all require a similar interaction pattern: users enter questions, the system retains context, returns answers progressively, and can call external tools to complete concrete operations. When developers build such applications from scratch, they commonly encounter problems in four areas: state management for multi-turn sessions, context trimming for long text, frontend rendering of streaming output, and migration of historical data.
This article aims to “replicate a basic conversational application.” It breaks down the required technical capabilities and provides architecture design, key code, and engineering considerations. The interface names and code in this article are illustrative. In actual implementation, the official documentation of the selected model service should be followed.
2. Core Capabilities
2.1 Multi-Turn Sessions and Context Management
The model itself does not store state. Each request must reorganize and send the historical messages. A common approach is to maintain a message list for each session, where each message contains a role, content, timestamp, and metadata. When the history length approaches the model context limit, trimming or summarization is needed: keep the system prompt and the most recent turns, and compress earlier content into a summary.
2.2 Streaming Output
If a long answer is displayed only after it is fully generated, users will notice the wait. Streaming output returns text in chunks, and the frontend appends and renders each segment. Implementation must handle three cases: network interruption, duplicated chunks, and user-initiated cancellation of generation.
2.3 Historical Session Import
Users often want to migrate existing conversation records to a new application. The import flow includes parsing exported files, normalizing them into an internal message structure, removing sensitive fields, sorting by time, and finally writing them to session storage. Format validation should be performed before import to prevent dirty data from polluting the index.
2.4 Tool Calling and Plugin Mechanism
Much of the value of a conversational application comes from tool calling. When the model determines that external capability is needed, it outputs a structured call request. The runtime executes the corresponding function and feeds the result back to the model. The plugin mechanism standardizes this process: each plugin declares its name, input parameters, output format, and permission scope.
2.5 Natural-Language Plugin Generation
Users describe requirements in natural language, and the system generates plugin code, completes installation, and runs it. This flow can be divided into four steps: requirement parsing, code generation, sandbox installation, and runtime validation. Each step needs clear input and output plus failure handling logic. Generated results must not enter the production environment directly.
3. Reference Architecture
A recommended design divides the system into five layers:
- Frontend layer: handles session lists, message rendering, streaming display, and file uploads.
- Gateway layer: handles authentication, rate limiting, request logging, and sensitive-information filtering.
- Session service: handles message persistence, context assembly, and history import.
- Model invocation layer: encapsulates request and retry logic and isolates protocol differences between service providers.
- Plugin runtime: executes tool calls in an isolated environment and records execution logs.
The main benefit of layering is low replacement cost. When the model service or storage solution changes, only the adapter in the corresponding layer needs to be modified, and the other layers are largely unaffected.
4. Key Implementation Examples
The following code is illustrative pseudocode used to explain data structures and processing flows. It does not correspond to any specific interface.
Session data model:
{"session_id": "s_20261125_0001","title": "API design discussion","created_at": "2026-11-25T08:30:00Z","messages": [{"role": "user", "content": "How should a paginated API be designed?", "ts": "2026-11-25T08:30:05Z"},{"role": "assistant", "content": "...", "ts": "2026-11-25T08:30:12Z"}],"summary": null}
Context assembly logic:
def build_context(session, max_tokens, count_tokens):system = session.get("system_prompt", "")budget = max_tokens - count_tokens(system)picked = []for msg in reversed(session["messages"]):cost = count_tokens(msg["content"])if cost > budget:breakpicked.append(msg)budget -= costreturn [{"role": "system", "content": system}] + list(reversed(picked))
This function takes values from the newest message backward until the budget is exhausted. If earlier content is still valuable, a separate summarization task should be called, the result should be written to the summary field, and then it should be assembled together with the recent messages.
Frontend handling of streaming output:
async function streamReply(client, messages, onChunk, signal) {const stream = await client.send({ messages, stream: true, signal });for await (const chunk of stream) {onChunk(chunk.text);}}
signal is used to cancel the request. When the user clicks stop, the frontend triggers cancellation, and the server should also terminate the corresponding generation task to avoid continuing to incur costs.
Field mapping for history import:
def normalize_message(raw):role = raw.get("role") or raw.get("author")if role not in {"user", "assistant", "system"}:raise ValueError(f"unknown role: {role}")return {"role": role,"content": str(raw.get("content", "")).strip(),"ts": raw.get("timestamp"),}
Unknown roles should raise an error directly and be logged; they must not be silently dropped. Otherwise, users may mistakenly believe that records have been fully migrated, and the problem will only surface later.
5. Engineering Considerations for Automatic Plugin Generation
It is difficult to guarantee the correctness and security of code generated from natural language in advance, so a fixed process is needed to control risk.
- Requirement structuring: Convert the user description into a specification containing inputs, outputs, dependencies, and permissions. Generate code only after the user confirms it.
- Least privilege: Plugins have no network access or file write permissions by default and can request permissions only according to the specification.
- Sandbox execution: Installation and execution are completed in an independent container or restricted process, with timeout, memory, and CPU limits.
- Automated testing: Generate test cases from the specification, and allow enablement only after all tests pass.
- Human review: Plugins involving data writes, external calls, or financial operations require human confirmation before going live.
This process separates “generation succeeded” from “safe to use.” The former only means the code can be produced; the latter requires passing tests and review.
6. Cost and Quality Evaluation
When evaluating a conversational application, it is advisable to focus on three types of metrics.
- Cost: The cost of a single session equals the number of input tokens multiplied by the input unit price, plus the number of output tokens multiplied by the output unit price. If plugin calls generate multiple rounds of model interaction, each round must be counted.
- Quality: Use a set of representative tasks to measure the first-pass rate, that is, the proportion of cases in which the model produces a usable result without manual modification. The evaluation set should cover real business problems, not only generic examples.
- Latency: Record the time to first token and the total time for a complete answer separately. The former determines perceived speed, and the latter affects throughput and unit cost.
After each model version change or prompt modification, rerun on the same evaluation set and save the results for before-and-after comparison. Without baseline data, any judgment that “the effect has improved” lacks a basis.
7. Security and Compliance
- Conversation content may contain personal information and trade secrets. Desensitize it according to rules before storage, and set retention periods.
- History import files should be parsed in an isolated environment, with file size limits to prevent malformed data from causing service abnormalities.
- API keys should be stored in environment variables or a secret management service and must not be written into code or logs.
- For external user scenarios, model output should undergo content moderation before display.
- External requests from plugins should be controlled by allowlists to prevent leakage of sensitive data.
8. Launch Checklist
- Version numbers have been defined for the data structures of sessions, messages, and plugins to facilitate future migration.
- Streaming output has been tested under network interruption, duplicated chunks, and generation cancellation scenarios.
- History import provides clear prompts for unknown fields and format errors.
- Plugin execution has timeout, resource limits, and logging.
- Cost and latency metrics have been integrated into monitoring and alerting.
- An evaluation set has been established, and baseline results for the current version have been saved.
9. Conclusion
The key to replicating a basic conversational application is not visual similarity, but whether capabilities such as session management, streaming interaction, data migration, and plugin execution are reliable. By decoupling model calls from business logic and incorporating plugin generation into testing and review processes, teams can obtain a maintainable system at controllable cost.
