Rebuilding a Chat App with Open APIs: Feature Breakdown, Model Selection, and Pitfalls
This article explains how to rebuild a chat application using open APIs while separating API access from model-weight licensing. It outlines a module-by-module implementation flow, compares six model-stack combinations with a shared test methodology, and provides checklists for streaming output, file uploads, key management, integration testing, and security review.
1. API Access and Open-Source Models Are Different
Some cloud providers expose APIs for chat, search, automatic speech recognition (ASR), and text-to-speech (TTS). Developers can follow mainstream chat applications to reproduce their core interactions, but public API access does not mean public model weights. The authorization scopes are different, and both must be confirmed separately before selection.
Use the following questions as a selection checklist:
- Can the model weights be downloaded, or is access available only through a cloud API?
- Does the license allow commercial use, and does it restrict redistribution or offering an independent service?
- Do the call quota, concurrency limit, and unit price match expected usage?
- Is request content used for model training? How long is data retained, and can this be disabled?
- Are there copyright or content-use restrictions on search results and voice assets?
When answers are unclear, rely on the service agreement and signed documents. Do not design products based on community rumors.
2. Feature Breakdown and Rebuild Flow
A chat application can be broken down into the following modules. For each module, document dependencies, permissions, versions, and inputs/outputs; otherwise, integration debugging becomes difficult.
- Chat module: Receives user messages and historical context, then returns a reply. The input is a message list and system prompt; the output is full text or streaming chunks. Manage context length and define a truncation strategy for overlong context.
- Search module: Retrieves external information based on the user question, then injects the results into the chat context. Record retrieval time, label sources, and define a citation format.
- ASR module: Converts user recordings into text. Unify sample rate, encoding format, and maximum duration, and handle silence and background noise.
- TTS module: Converts replies into audio. Select voice and speaking rate, segment long text for synthesis, and cache repeated content.
- UI reproduction: Implement the message list, input box, voice button, and file entry according to the design. The UI is responsible only for display and interaction; it must not store keys directly or call models directly.
- Exception handling: Distinguish network timeouts, insufficient quota, content moderation blocks, and format errors, and provide user-understandable prompts.
- Integration testing: Use fixed samples to verify the input and output of each module, then run end-to-end tests.
- Security review: Check keys, permissions, logs, uploaded files, and content safety policies.
It is recommended to first build a minimal closed loop for chat and UI, then gradually add search and voice. Each time a module is added, rerun the integration test cases.
3. Comparing Six Model Combinations
The table below lists six combination approaches. The combination names are based on capability and cost orientation; actual model names should be replaced with the specific models offered by your cloud provider.
| Combination | Chat model | Search source | ASR | TTS | Focus |
|---|---|---|---|---|---|
| Combination 1 | High-capability chat model | Cloud provider search API | High-accuracy ASR | High-naturalness TTS | Answer quality; high per-call cost |
| Combination 2 | High-capability chat model | Self-hosted retrieval | General-purpose ASR | Standard TTS | Controllable retrieval results |
| Combination 3 | Lightweight chat model | Cloud provider search API | General-purpose ASR | Standard TTS | First-token latency and cost |
| Combination 4 | Lightweight chat model | Self-hosted retrieval | Lightweight ASR | Lightweight TTS | Low cost; limited offline scenarios |
| Combination 5 | Mid-tier chat model | Cloud provider search API | Real-time streaming ASR | Low-latency TTS | Voice conversation experience |
| Combination 6 | Mid-tier chat model | Self-hosted retrieval | High-accuracy ASR | High-naturalness TTS | Chinese-language voice and professional scenarios |
When comparing, all combinations must use the same test methodology; otherwise, the numbers are not comparable:
- First-token latency: Time from user send to receipt of the first streaming chunk.
- Full response time: Time from send to receipt of the complete reply.
- Per-conversation cost: Calculated from actual token usage and number of calls.
- ASR error rate: Character error rate calculated on the same set of recordings.
- TTS quality: Blind human rating, with at least two raters per sample.
- Search hit rate: Human-labeled relevance of retrieved results to the question.
Use the same set of questions, the same network environment, and the same concurrency level. Run each metric at least three rounds, take the median, and record the test date, because cloud model versions and prices can change at any time.
There is no universal optimum. Selection depends on the goal:
- If first-token latency and cost are priorities, choose a lightweight chat model plus streaming ASR.
- If answer quality is the priority, choose a high-capability chat model and cache results for common questions.
- If voice is the core feature, test ASR error rate first, then decide on the chat model.
4. Streaming Output Issues and Checklist
Streaming output can significantly improve the perceived waiting experience, but it is prone to out-of-order chunks, broken streams, and duplicate generation.
Checklist:
- When the backend forwards chunks, preserve sequence numbers; the frontend should assemble them by sequence number rather than arrival order.
- Set both a first-chunk timeout and an overall timeout, and provide a retryable prompt after timeout.
- After a connection interruption, keep the content already output; on retry, clarify whether it is continuation or regeneration.
- When the user stops actively, the backend should cancel the upstream request in sync to avoid continued billing.
- Set a retry limit and use exponential backoff to prevent amplifying rate-limit pressure.
- On a rate-limit response, queue according to the returned wait time; do not resend immediately.
5. File Upload Checklist
File upload is one of the easiest places to overlook security risks. Uploaded content may contain malicious files, oversized files, or sensitive information.
Checklist:
- Set a type whitelist, for example allowing only txt, pdf, png, and mp3.
- Limit the size of a single file and the number of files per upload.
- On the server side, determine the real type from the file header rather than relying only on the extension.
- Validate early on the frontend to reduce invalid uploads, but the server must validate again.
- Store files in object storage first, then have the backend generate a short-lived access credential for the parsing service.
- Scan files for viruses and detect sensitive content.
- When parsing fails, return a clear error reason without exposing internal exception stacks to the user.
- Set a file retention period and provide an entry point for users to delete files.
6. Key Management
Key leakage is one of the most serious consequences in a rebuild project. Once a key enters frontend code or a public repository, others may directly consume your quota.
Checklist:
- Do not write keys into frontend code, mini-program packages, mobile app installers, or public repositories.
- Store keys in environment variables or a key management service, with separate configurations for development, testing, and production.
- Create an independent sub-account for each service and grant only the required API permissions.
- Rotate keys regularly and ensure they can be revoked quickly after a leak.
- Mask the Authorization request header and user personal information in logs.
- Set budget alerts and usage limits for each key.
7. Integration Testing and Common Errors
The table below lists common symptoms, causes, and handling methods during integration.
| Symptom | Common cause | Handling method |
|---|---|---|
| Streaming output out of order | Chunks lack sequence numbers, or concurrent writes go to the same buffer | Add sequence numbers to chunks; assemble in order on the frontend |
| File upload fails | Exceeds size limit, type mismatch, or network interruption | Validate early on the frontend; use chunked upload for large files |
| Speech not recognized | Sample rate or encoding format does not match API requirements | Transcode uniformly to the format required by the API |
| Frequent response timeouts | Context is too long, or concurrency exceeds quota | Truncate historical messages; add a request queue |
| Quota exhausted quickly | Retry strategy is out of control, or the service is abused by third parties | Limit retries; enable user-level rate limiting |
| Key leaked | Hardcoded or called directly from the frontend | Migrate to the backend and rotate the key immediately |
8. Security and Compliance Review Checklist
Before launch, check each item below. Each item should have a clear pass or fail conclusion; failed items must be fixed before launch.
- Are keys present only in the backend or a key management service?
- Does each service account have only the minimum necessary permissions?
- Do logs mask keys, tokens, and user privacy information?
- Have uploaded files undergone type validation, size limits, and security scanning?
- Is a content safety policy configured to block violating input and output?
- Does the user data retention period comply with the terms of service and local regulations?
- Is the privacy policy shown to users, and is there a way to delete data?
- Have the usage authorizations for search results, voice assets, and model output been confirmed?
Conclusion
When rebuilding a chat application, first confirm the authorization boundaries of APIs and models, then complete the feature breakdown and minimal closed loop. Model selection should balance latency, cost, licensing, voice quality, and search capability, and should be tested with the same methodology. Streaming output, file uploads, and key management are the most error-prone areas; check them against the lists above before integration testing.
