Open-Source LLM AI App Replication: Model Selection and Implementation Checklist

    This article presents a practical checklist for replicating an AI assistant with open-source models. It covers API limits and project boundaries, model-combination comparisons and reproducible evaluation methods, a runnable FastAPI proxy skeleton, sandboxed frontend generation, and long-context storage, privacy, and logging safeguards.

    1. Challenges and Boundaries

    The open-source ecosystem lets developers obtain model weights, interface definitions, and even some client code. With these components, developers can replicate a functionally similar AI assistant at high fidelity. However, there is still a clear gap between “getting it to run” and “keeping it running reliably over time.”

    Public APIs commonly impose rate limits such as daily conversation caps and maximum input length per request. These limits directly affect long-text processing, conversation history storage, and multi-turn code generation. Therefore, a replication project must first answer three questions: how much context the business needs, how many calls it will generate per day, and whether data can leave the internal network.

    The conclusions in this article are based on reproducible evaluation methods, not the ranking of a single experiment. The article does not provide specific performance numbers. Readers should re-measure with their own task sets and model versions before making selection decisions.

    2. Model Combination Comparison and Evaluation Method

    The table below lists five common combinations. For each one, record the specific model name, version number, call date, temperature parameter, and maximum output length; otherwise, the test results cannot be reproduced.

    Combination Role Suitable Scenarios Main Risks Metrics to Record
    High-throughput model plus multi-agent collaboration framework Handles rapid iteration and project initialization Prototype validation, high-frequency small changes Peer review among roles may amplify the same error First-token latency, total time, compile pass rate
    Closed-source flagship model plus IDE coding assistant Tests the upper limit of a single model for long code generation Complex logic, full-stack generation Dependency on external services, cost, and data egress risk Run pass rate, per-task token cost
    Another closed-source top-tier model plus IDE tool Serves as a second control group Compares code style and architectural understanding Control conclusions apply only to the selected task set Same metrics as the second group, plus lines manually modified
    Ultra-long-context model plus standard model plus general client Long-context model provides global memory; standard model handles daily interaction Large codebase analysis, historical log summarization High long-context cost; full input may exceed budget Context utilization, recall accuracy, per-call cost
    Cloud provider foundation model plus official client Out-of-the-box use with less integration work Teams that need rapid launch and already have cloud resources High migration cost, interface lock-in Integration time, availability, failure recovery time

    For evaluation, use a fixed task set. The task set can contain about twenty full-stack requirements, such as a to-do app, a chat room with login, and a data dashboard with charts. Run each task three times, and take the average and fluctuation range.

    Core metrics are as follows:

    • Compile pass rate: whether generated code passes the build command.
    • Run pass rate: whether core use cases pass after the application starts.
    • First-token latency and total time: reflect interactive experience and batch generation efficiency, respectively.
    • Per-task cost: input and output token counts multiplied by unit price, plus extra consumption caused by retries.
    • Lines manually modified: the number of lines a senior engineer must change to bring generated code to a mergeable state.

    3. A Runnable Backend Skeleton

    The backend uses FastAPI and routes requests to different models through a unified proxy layer. The code below can run directly, but it requires three model identifiers and a gateway address compatible with the OpenAI API format.

    1. import asyncio
    2. import os
    3. import uuid
    4. from typing import Any
    5. import httpx
    6. from fastapi import FastAPI, HTTPException
    7. from pydantic import BaseModel
    8. API_BASE = os.environ["MODEL_API_BASE"]
    9. API_KEY = os.environ["MODEL_API_KEY"]
    10. ROUTING = {
    11. "long_context": os.environ["MODEL_LONG_CONTEXT"],
    12. "code": os.environ["MODEL_CODE"],
    13. "chat": os.environ["MODEL_CHAT"],
    14. }
    15. RETRYABLE = {429, 500, 502, 503}
    16. app = FastAPI()
    17. client = httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=5.0))
    18. class ChatRequest(BaseModel):
    19. messages: list[dict[str, Any]]
    20. request_id: str | None = None
    21. def classify_task(messages: list[dict[str, Any]]) -> str:
    22. total_chars = sum(len(str(m.get("content", ""))) for m in messages)
    23. last_text = str(messages[-1].get("content", "")).lower()
    24. if total_chars > 50_000:
    25. return "long_context"
    26. if any(word in last_text for word in ("代码", "函数", "接口", "bug", "code")):
    27. return "code"
    28. return "chat"
    29. async def call_model(model: str, messages: list[dict[str, Any]], max_retries: int = 2) -> str:
    30. url = f"{API_BASE}/chat/completions"
    31. headers = {"Authorization": f"Bearer {API_KEY}"}
    32. body = {"model": model, "messages": messages, "temperature": 0.2}
    33. for attempt in range(max_retries + 1):
    34. try:
    35. resp = await client.post(url, json=body, headers=headers)
    36. except (httpx.TimeoutException, httpx.ConnectError):
    37. if attempt == max_retries:
    38. raise HTTPException(status_code=504, detail="model timeout")
    39. await asyncio.sleep(2 ** attempt)
    40. continue
    41. if resp.status_code in RETRYABLE and attempt < max_retries:
    42. await asyncio.sleep(2 ** attempt)
    43. continue
    44. if resp.status_code != 200:
    45. raise HTTPException(status_code=502, detail=f"model error {resp.status_code}")
    46. return resp.json()["choices"][0]["message"]["content"]
    47. raise HTTPException(status_code=502, detail="model unavailable")
    48. @app.post("/api/chat")
    49. async def chat(req: ChatRequest):
    50. if not req.messages:
    51. raise HTTPException(status_code=400, detail="messages is empty")
    52. request_id = req.request_id or str(uuid.uuid4())
    53. task = classify_task(req.messages)
    54. model = ROUTING[task]
    55. answer = await call_model(model, req.messages)
    56. print(f"request_id={request_id} task={task} model={model}") # Log metadata only, not conversation content
    57. return {"request_id": request_id, "task": task, "answer": answer}

    Before running, the following conditions must be met:

    • Python 3.10 or later, because the code uses the str | None syntax.
    • Dependencies fastapi, uvicorn, httpx, and pydantic must be pinned to specific versions and written into requirements.txt.
    • Inject secrets through environment variables; do not write secrets into code or commit them to the version repository.
    • The startup command is uvicorn main:app --host 127.0.0.1 --port 8000; in production, place it behind a reverse proxy.

    The classification rules in the code are only a starting point. Keyword classification is prone to false positives. Before launch, use the task set to check classification accuracy, and consider using a small model for intent classification.

    4. Frontend Generation and Sandbox Execution

    In combinations one and two, frontend code generated by the model needs to go through compilation and runtime verification. A common flow is: the model outputs a React or Vue component, the sandbox executes the build command, and compile errors are sent back to the model as new input for repair. This loop is usually capped at two to three rounds; beyond that, hand off to a human.

    The sandbox must meet the following requirements:

    • No external network access, to prevent generated code from reading or exfiltrating sensitive data.
    • Limit CPU, memory, and execution time; a single build timeout is recommended at three to five minutes.
    • Use temporary directories and destroy the container after each run; do not retain credentials in generated artifacts.
    • Forbid generated code from directly accessing the host file system and environment variables.

    The automatic repair loop also increases token consumption. Evaluation should include repair rounds in the per-task cost; otherwise, real overhead will be underestimated.

    5. Long-Text Storage and Security

    To handle per-request input length limits, a common approach is to separate conversation memory from the model context and use an “object storage plus vector database” structure. The following thresholds are only starting values and should be adjusted based on the task set.

    • Short-term memory: keep the raw text of the most recent twenty turns and stay within about 8,000 tokens.
    • Compression trigger: after the threshold is exceeded, asynchronously call a summarization task, compress older conversations into summaries, and store them in object storage.
    • Retrieval strategy: use vector retrieval with topK set to five and set a similarity lower bound; content below the lower bound is not injected into the prompt. After recall, a reranking model can improve precision.
    • Persistence order: only after the summary is successfully written can the original conversation be deleted, avoiding loss of historical data if an asynchronous task fails.

    Privacy and permission requirements are equally important:

    • Redact before persistence: use regular expressions to identify fields such as phone numbers, ID numbers, and bank card numbers, and use named entity recognition to handle names and addresses.
    • Set object storage to a private bucket, and grant the service account only the minimum permissions required for reading and writing.
    • Encrypt data at rest and set a retention period, for example, automatic deletion after thirty days.
    • Users can query and delete their own history; deletion operations must also clean the vector index.

    Code logs also carry leak risks. The sample code logs only the request ID, task type, and model name, not the conversation body.