Large Language Model Application Development: Technology Selection and Implementation Practices

    This article presents a vendor-neutral framework for building production LLM applications, covering a five-layer decoupled architecture, multi-model routing and cost control, retrieval-augmented generation quality, agent orchestration safeguards, observability and evaluation, and security defaults. It includes interface contracts, a cache key example, an orchestration configuration sample, a retrieval evaluation metric table, and a pre-launch checklist to help teams keep engineering capability in-house while models and tools change.

    1. Why Technical Discussions Lose Focus

    At a recent industry conference, a technical manager’s personal appearance and social media profile were widely shared, and the discussion quickly shifted from “how good are his code and architecture decisions” to private topics unrelated to engineering. The genuinely useful questions in the comments were buried: what architectural trade-offs did the LLM application platform he led make? How is retrieval augmentation recall quality guaranteed? How does agent orchestration roll back a failure?

    This pattern is not irrelevant to developers. It is a reminder that technology selection must return to verifiable metrics and reproducible engineering processes, rather than judgments based on the popularity of a tool, a person, or an event. The discussion below stays at the general technical level and offers a practical framework decoupled from any specific vendor.

    2. Overall Architecture: Five Decoupled Layers

    A sustainable LLM application can usually be split into five layers:

    1. Access layer: session management, authentication, rate limiting, and multi-model routing;
    2. Orchestration layer: task decomposition, tool invocation, flow control, and rollback;
    3. Capability layer: model inference, vector retrieval, reranking, and content moderation;
    4. Data layer: raw documents, chunks, vector indexes, and structured metadata;
    5. Observability layer: logs, metrics, tracing, and evaluation regression.

    The key principle is interface convergence. Each layer exposes only a stable abstract interface, and the concrete implementation stays replaceable. A schematic, language-agnostic definition of the contracts:

    1. interface ModelProvider {
    2. chat(messages, params) -> {text, usage, latency}
    3. embed(texts) -> vector[][]
    4. }
    5. interface Retriever {
    6. search(query, topK, filters) -> Chunk[]
    7. }
    8. interface Tool {
    9. schema() -> JsonSchema
    10. invoke(args) -> Result
    11. }

    The benefit is that when a model tier raises prices, gets rate limited, or is retired, only the implementation class needs replacing, with no changes to business code. When retrieval evolves from pure vector search to a hybrid of keyword and vector search, the orchestration layer is unaffected.

    3. Model Access: Multi-Model Routing and Cost Control

    A single model rarely satisfies quality, latency, and cost requirements at the same time. Three routing strategies are common in practice:

    • Route by task tier: simple tasks such as intent recognition and field extraction go to smaller models, while complex reasoning and long-form writing go to larger ones;
    • Route by context length: short contexts take a low-latency channel, long contexts take a channel with a large window, and overly long inputs are segmented and summarized first;
    • Degrade by priority: when the primary channel times out or hits a rate limit, traffic switches automatically to a backup channel and the response is marked as degraded.

    Cost control cannot rely on “fewer calls” alone; it depends even more on “less useless context.” Quantifiable measures include deduplicating prompt templates, rolling summaries of conversation history, truncating retrieval results by relevance, and semantic caching for frequent repeated questions. Cache key design must include the model identifier, prompt version, and key parameters, otherwise a subtle defect appears: the template changed but old answers are still served from cache.

    1. def cache_key(model, prompt_version, query, params):
    2. payload = json.dumps(
    3. {"m": model, "v": prompt_version, "q": query, "p": params},
    4. sort_keys=True, ensure_ascii=False
    5. )
    6. return hashlib.sha256(payload.encode("utf-8")).hexdigest()

    4. Knowledge Base and Retrieval Augmentation: The Core of Answer Trustworthiness

    Most hallucination mitigation lands on retrieval quality. Engineering practice suggests splitting retrieval into four steps and measuring each one:

    1. Document parsing: restore structure for tables, headers and footers, and code blocks, avoiding semantic fragmentation caused by treating a whole page as plain text;
    2. Chunking strategy: split on semantic boundaries, keep moderate overlap between chunks, and attach metadata such as source, section, and last updated time to every chunk;
    3. Hybrid recall: keyword retrieval handles exact matches for proper nouns and identifiers, vector retrieval handles semantic similarity, and the two result sets are merged with weighted fusion;
    4. Reranking and truncation: rerank candidates with a cross-encoder or rule-based scoring, and pass only highly relevant fragments into the model context.

    Evaluation requires a regression set. A minimal viable metric set:

    Metric Meaning Reference approach
    Recall hit rate Whether the correct chunk enters the candidate set Manually label 200-500 question-answer pairs
    Context effectiveness Share of context fragments actually cited Record cited fragment IDs
    Answer faithfulness Whether the answer can be derived from the context Sampled human review or model cross-evaluation
    First token latency Perceived response speed Report P95 per channel

    One point deserves emphasis: do not swap embedding models or chunking parameters without a regression set, or quality changes cannot be attributed.

    5. Agent Orchestration: Controllability Over Freedom

    The value of an agent lies in calling tools to complete multi-step tasks, and the risk lies in the same multi-step nature. Controllable orchestration usually includes four mechanisms:

    • Explicit state machine: define tasks as finite states so the model cannot freely decide the flow and create infinite loops;
    • Tool allowlist and parameter validation: all tool arguments must pass structured schema validation, and unauthorized calls are rejected outright;
    • Step and budget limits: set a maximum iteration count, a maximum token budget, and a timeout; on exceeding any of them, terminate and return partial results;
    • Idempotency and compensation: write tools must support idempotency keys, and failures trigger compensating actions rather than blind retries.
    1. {
    2. "state": "need_weather",
    3. "max_steps": 6,
    4. "budget_tokens": 8000,
    5. "tools": ["weather_query"],
    6. "on_exceed": "return_partial_with_notice"
    7. }

    For high-risk actions such as deleting data, sending messages externally, or operations that incur charges, a human confirmation step should be mandatory, and the confirmation record should be written to an audit log.

    6. Observability and Evaluation: Making Quality Changes Attributable

    Debugging LLM applications is harder than debugging traditional services because output is nondeterministic. Observability is best split into three data types:

    1. Runtime logs: request ID, routed model, prompt version, retrieved fragment IDs, and latency breakdown;
    2. Quality metrics: faithfulness, refusal rate, tool call success rate, and human correction rate;
    3. Evaluation regression: run a fixed regression set on every prompt or model change and produce a comparison report.

    Tracing must answer “which step produced this wrong answer”: did retrieval fail to recall, did reranking push the correct fragment down, or did the model ignore the context? Without this attribution capability, teams can only iterate on prompts repeatedly, which is extremely inefficient.

    7. Security and Compliance: Least Privilege by Default

    • Data classification: three tiers of public, internal, and sensitive; sensitive data is masked or processed locally before entering the model;
    • Output moderation: filter both directions for prompt injection, unauthorized instructions, and sensitive content, treating user input as untrusted as well;
    • Permission isolation: knowledge base filters are injected as mandatory conditions per tenant and role, never left to prompt instructions that “ask” the model to comply;
    • Audit trail: who queried which data source and when must be traceable to an individual.

    Note that any approach of “stuffing all documents directly into the context” is unsustainable for both permissions and cost.

    8. Pre-Launch Checklist

    • Is there a multi-model degradation path, and is the degraded state visible to users;
    • Is a retrieval regression set of at least two hundred items in place and included in the release process;
    • Do all tool arguments pass structured validation, and are write operations idempotent;
    • Are the three limits of steps, budget, and timeout configured;
    • Can a request be traced back to the retrieved fragments by request ID;
    • Is sensitive data classified and masked, and is permission filtering enforced server-side.

    9. Conclusion

    Back to the discussion at the beginning: what deserves attention is never the popularity of a person or a tool, but verifiable architecture layering, measurable retrieval quality, rollback-capable orchestration, and a traceable observability system. Implementing this framework gives a team a technology foundation independent of any specific vendor: models can change, tools can change, and engineering capability stays in your own hands. For a faster engineering start, deployment and observability loops can be built on general capabilities such as container platforms, object storage, log services, and monitoring and alerting from Baidu AI Cloud, keeping effort focused on data and evaluation, the two areas that truly determine quality.