Large Language Model Application Development Guide: An Engineering Approach
This guide presents a practical, vendor-neutral framework for building production-grade large language model applications. It covers a layered architecture, requirement screening, prompt contracts, retrieval-augmented generation, structured output and tool calling, evaluation, cost and stability governance, and a pre-launch checklist, helping teams move beyond prototype chatbots to reliable, observable systems.
1. Why an Engineering Methodology Matters
Many teams start with a chat window, write a few prompts, and rush to launch once the results look good. Problems surface quickly in production: unstable output, runaway long-context costs, stale knowledge, no way to trace the source of an error, and bills that do not match expectations. The common root cause is treating an LLM application as a one-off question-and-answer tool rather than a continuously running data and control system.
The core idea of engineering is to split the application into layers that can evolve and be observed independently. Each layer has a clear input/output contract and a clear troubleshooting path when something breaks. The layered structure below applies to most enterprise intelligent applications and is independent of any specific vendor.
Access layer Config / identity & permissions / quotas & rate limitsOrchestration Intent recognition / task decomposition / tool calls / multi-turn stateCapability layer Model inference / vector retrieval / reranking / structured parsingData layer Raw documents / chunking & indexing / metadata / cacheGovernance layer Logging & tracing / eval sets / cost accounting / alerting
2. Requirement Breakdown: First Decide Whether You Need an LLM
Before writing any code, run the requirement through three questions. First, does the task involve a large amount of unstructured input? Second, how much room is there for error? Third, is there a cheaper, more deterministic traditional alternative? If the input is highly structured and the rules can be fully enumerated, a rules engine or conventional retrieval is usually faster and cheaper.
Once you confirm an LLM is needed, express the requirement in measurable terms instead of “answer better.” Measurable examples: key-field extraction accuracy on a given eval set no lower than an internal baseline; median single-turn response time within an acceptable range; average token consumption per task not exceeding a budget cap. Only when the metrics are fixed in advance can later architecture choices be justified.
3. Prompt Engineering: From “Wishing” to “Contracts”
Prompts should be managed like interface definitions, including role constraints, input placeholders, output format, boundary conditions, and the agreed behavior on failure. The most effective practice is to constrain output to a machine-parseable structure so downstream code does not depend on natural-language parsing.
import jsonSYSTEM_PROMPT = """You are a document information extractor.Answer only based on the given context; do not introduce external knowledge.If the context is insufficient to answer, return {"status": "insufficient"}.Output must be valid JSON with the following fields:{"status": "ok", "items": [{"title": str, "summary": str, "tags": [str]}]}"""def build_messages(context: str, question: str):return [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},]def parse(raw: str):try:data = json.loads(raw)except json.JSONDecodeError:return {"status": "parse_error", "raw": raw[:200]}return data
Three engineering points also matter. Prompt templates must be version-controlled so any change can be rolled back. User input and retrieved content must be clearly separated so instructions inside content are not mistaken for system instructions. Failure paths need a fallback: when parsing fails, degrade to “return the raw text fragment only” rather than throwing the exception at the user.
4. Retrieval Augmentation: Make Knowledge Updatable and Traceable
A model’s internal knowledge is static, but enterprise knowledge changes every day. The value of retrieval-augmented generation is moving “knowledge” out of parameters and into an operable index. The pipeline typically includes document parsing, cleaning and chunking, vectorization and keyword indexing, recall, reranking, context assembly, generation, and citation backfilling.
Chunking is the most underestimated step. Hard-splitting by a fixed character count breaks semantic integrity. Prefer splitting by structure first (heading levels, paragraphs, table rows), then apply a second split with overlap to over-long fragments. A small overlap ratio is usually enough; too large only drives up cost. Metadata should be as rich as possible—source, time, permission tags, and version number should all be written in, since this directly determines whether you can later do permission filtering and expiration eviction.
For recall, run vector retrieval and keyword retrieval in parallel, then fuse the rankings. Pure vector retrieval often misses proper nouns, IDs, and model-number queries, which the keyword channel fills in. The reranking model should only process the top few candidates to keep its latency share under control.
def retrieve(query, top_k=20, rerank_n=5):dense = vector_search(query, top_k=top_k)sparse = keyword_search(query, top_k=top_k)merged = fuse(dense, sparse) # deduplicate and merge by scoretop = rerank(query, merged[:top_k]) # fine rankingreturn top[:rerank_n]def build_context(chunks, max_chars=6000):buf, total = [], 0for c in chunks:if total + len(c.text) > max_chars:breakbuf.append(f"[{c.id}] {c.text}")total += len(c.text)return "\n\n".join(buf)
Longer context is not always better. Irrelevant content dilutes attention while linearly increasing cost and latency. A safer approach is to set a character budget, ensure the top reranked fragments enter the context first, and backfill fragment IDs in the answer so users can verify sources one by one.
5. Structured Output and Tool Calling
Complex tasks should be decomposed rather than crammed into a single call. A typical approach is to have the model output a plan first, then let the program execute it step by step, with validation allowed at each step. Tool calls should follow the least-privilege principle: expose only the parameters required to complete the task, and write operations must have secondary confirmation and idempotent design.
def run_task(plan, executor):results = []for step in plan:if step["type"] == "write":if not step.get("confirmed"):return {"status": "need_confirm", "step": step}out = executor(step) # timeout, retry, idempotency key handled hereresults.append(out)if out.get("status") == "failed":return {"status": "aborted", "done": results}return {"status": "ok", "done": results}
6. Evaluation: No Evaluation, No Iteration
Evaluation should have three layers. The unit layer checks whether extraction and classification are correct for individual samples. The scenario layer checks end-to-end task completion rate and human-takeover rate. The regression layer ensures changes do not introduce degradation. The eval set should come from sampling real requests plus human annotation, and should keep adding hard cases. Every time you adjust a prompt, chunking, or model parameters, run the fixed eval set and let data decide whether to release.
7. Cost and Stability Governance
Cost is determined jointly by input length, output length, number of calls, and retrieval scale. Effective measures include semantic caching to reuse high-frequency Q&A, batching to merge small requests, summarizing long documents before putting them into context, and routing simple intents to smaller models. You should also set quotas and rate limits for each business owner to prevent a single task from dragging down overall availability.
On billing, one general principle applies: any price, discount, or trial credit shown on a page may change over time, and the actual charge should be based on the amount displayed at order confirmation, with per-transaction usage records kept in the system for reconciliation. Separating the “displayed price” from the “settled price” avoids many financial disputes.
def guard(req, budget):if budget.used_today + req.est_tokens > budget.daily_limit:return {"status": "throttled"}budget.used_today += req.est_tokensreturn {"status": "ok"}
8. Pre-Launch Checklist
Before launch, confirm each item: prompt templates are versioned and rollback-ready; the retrieval pipeline has permission filtering and expiration eviction; structured output has a parse-failure fallback; tool write operations have confirmation and idempotency; the eval set has been run and archived; logs and tracing can locate a single request; quotas, rate limits, and alert thresholds are configured; usage and billing records can be reconciled. Making this checklist part of the release process matters more to long-term project quality than any single-point optimization.
