Large Language Model Engineering in Practice: How to Build Reliable AI Applications Without Writing Algorithms

    This article explains how to engineer large language model (LLM) applications without developing algorithms yourself. It reframes LLMs as probabilistic systems rather than deterministic ones, then breaks engineering work into four control planes: prompt engineering for output structure, RAG for factual grounding, function calling for authorized actions, and standardized model context protocols for integration. You will find practical guidance on structured output contracts, RAG data and evaluation practices, tool permission and audit design, a five-layer reference architecture, a phased rollout plan, and a governance checklist for avoiding common anti-patterns.

    1. Start With the Right Mental Model: LLMs Are Probabilistic Systems, Not Black Magic

    Many teams repeatedly struggle with LLM projects, and the root cause is often not model capability but a mismatch in expectations: treating a probabilistic system as a deterministic one. An LLM fundamentally samples the next token based on probability given a context. The same input can produce different phrasing under different temperatures and sampling strategies. It has no built-in fact-checking step, and it does not inherently know what it does not know.

    The first principle of engineering is therefore this: do not try to eliminate uncertainty with longer prompts. Contain it instead. A practical approach is to split the system into four control planes:

    • Output control plane (PE, prompt engineering): constrain the role, task boundaries, output structure, and refusal conditions.
    • Knowledge control plane (RAG, retrieval-augmented generation): move the source of facts from parametric memory to external knowledge that is updatable and traceable.
    • Execution control plane (Function Calling): turn the model from something that “can talk” into something that “can act,” but only on authorized actions.
    • Interconnection control plane (standardized model context protocol ideas such as MCP): connect data sources, tools, and prompt context to the model in a unified way to reduce repeated integration costs.

    These four planes are independent yet complementary. Prompt engineering alone cannot guarantee factual accuracy. A knowledge base alone still cannot trigger business actions. Tools alone leave permissions and auditing out of control. The goal of engineering is not to pick one but to assemble all four into a closed loop.

    2. Output Control Plane: Replace “Prayer-Style Prompting” With Structured Constraints

    Prompt engineering is not a collection of magic spells; it is interface design. Split prompts into four sections: role and goal, input contract, output contract, and exception policy. The output contract is the most critical. It should explicitly define fields, types, enums, and null semantics so downstream code can parse the result directly.

    1. Role: You are a ticket dispatch assistant. Answer only based on the given knowledge chunks.
    2. Input: JSON containing {ticket_text, knowledge_chunks[], allowed_actions[]}
    3. Output: Strict JSON with fields:
    4. { "intent": "enum value", "confidence": 0~1, "answer": "string",
    5. "citations": ["chunk_id"], "action": null | {"name":"...", "args":{}} }
    6. Exception: When evidence is insufficient, confidence < 0.6, answer states the missing information, and action must be null.

    Three supporting engineering practices matter. First, fix decoding parameters per scenario: keep randomness very low for extraction and classification tasks, allow more for creative tasks, and store these parameters in configuration rather than scattering them across code. Second, validate outputs and repair them automatically: if parsing fails, feed the error message back to the model for one retry; if it still fails, fall back to a default branch. Never let dirty data flow into business systems. Third, build a regression evaluation set: turn real business samples into fixed test cases, run them whenever you change models or prompts, and track task success rate, format compliance rate, and refusal accuracy rather than relying on a few examples that “feel good.”

    3. Knowledge Control Plane: RAG Success Depends on Data and Evaluation, Not the Vector Store

    RAG is often misunderstood as “just connect a vector search and you are done.” What actually determines quality is data governance and evaluation. Break the pipeline into six observable steps: collection, cleaning, chunking, indexing, retrieval, and generation, with metrics for each.

    • Chunk along semantic boundaries rather than fixed character counts. Preserve heading hierarchy and table structure, and generate a stable ID for each chunk so it can be cited.
    • Use a hybrid retrieval strategy: keyword recall handles proper nouns and identifiers, vector recall handles semantically similar phrasing, and a reranking model narrows down candidates.
    • Enforce citation-based answers during generation. Output chunk IDs as an evidence chain to support manual spot checks and online accountability.
    • Keep permissions aligned with retrieval at the same source. Content a user is not allowed to see must never enter the candidate set, avoiding “retrieval bypassing authorization.”

    For evaluation, measure retrieval hit rate and evidence sufficiency separately from answer correctness. If retrieval fails to recall, the problem lies in data and indexing. If it recalls but the answer is wrong, the problem lies in prompting and generation constraints. Separating these two causes is the single most effective step for improving team efficiency. Knowledge updates must also be engineered: document changes should trigger incremental index rebuilding and record a version number so any answer can be traced back to a specific knowledge version.

    4. Execution Control Plane: Separate Capability From Permission in Function Calling

    Function calling lets the model output a structured call intent, while business code executes the real action. The core of secure design is to treat the model as an untrusted advisor: it can propose but cannot decide.

    1. {
    2. "name": "create_refund_ticket",
    3. "args": { "order_id": "A1024", "reason": "damaged in transit", "amount": 59.9 },
    4. "risk": "write",
    5. "approval": "required"
    6. }

    Key implementation points include: write tool descriptions that clearly state when the tool applies and when it does not to reduce misuse; validate parameters with strict typed schemas and reject out-of-range or missing values outright; classify tools by read/write attributes and introduce human confirmation or secondary approval for write and financial operations; log the input, output, latency, and model version of every call to form an auditable trail; and set timeouts, retry limits, and idempotency keys to prevent irreversible incidents such as duplicate orders. In addition, prepare a fallback path for every tool. When a tool is unavailable, tell the user clearly instead of letting the model fabricate an execution result.

    5. Interconnection Control Plane: Standardized Protocols Solve the N×M Integration Explosion

    When a team uses multiple models and multiple internal systems at the same time, integration costs grow multiplicatively. The value of a standardized model context protocol is to unify how models, data sources, and tools connect: data sources and tools expose capability manifests under a common specification, and the model side implements the protocol once and reuses it. Prompt context, resource reads, and tool calls all follow the same semantics. Adding a new knowledge source or internal system then does not require building an adapter layer for every model.

    Engineering recommendations: register capability manifests centrally and version them; expose sensitive resources only to the minimum necessary extent; handle authentication, rate limiting, masking, and auditing uniformly at the gateway layer; and keep trace identifiers across the protocol call chain to determine whether a data source or the model is slow. If you use general cloud capabilities, you can store raw documents in object storage, decouple index building with a message queue, run retrieval and tool services on a container platform, and rely on logging, monitoring, and alerting services for observability. These general categories are enough to support a clean architecture without binding to any proprietary interface.

    6. Assembling the Four Planes Into a Closed Loop: A Deliverable Reference Architecture

    A recommended top-down five-layer architecture:

    • Access layer: handles sessions and identity.
    • Orchestration layer: handles intent recognition, flow control, and multi-turn state.
    • Control layer: PE, RAG, function calling, and protocol adaptation.
    • Capability layer: models and tools.
    • Governance layer: spans the full stack and handles evaluation, canary releases, cost, and auditing.

    Roll out in three phases. Phase one delivers read-only Q&A to validate knowledge quality and citation trustworthiness. Phase two opens low-risk write operations with approval and idempotency in place. Phase three enables multi-tool collaboration and cross-system workflow automation while turning on canary releases and automatic rollback. For cost control, narrowing context through retrieval, using smaller models for classification and extraction, and applying semantic caching to high-frequency requests are usually more effective than switching to a larger model.

    7. Common Anti-Patterns and a Governance Checklist

    Anti-patterns include: hard-coding prompts as business logic; switching models without an evaluation set; retrieval without permission filtering; tools without idempotency and timeouts; and logs that omit the model version, making issues impossible to reproduce. The governance checklist can be reduced to six questions: Is the output strongly schema-validated? Does every answer carry evidence citations? Is knowledge incrementally updatable and traceable? Are write operations graded and approved? Are calls auditable across the full chain? Does every change run the regression evaluation?

    The conclusion is straightforward: you can do LLM engineering well without studying algorithms, as long as you treat uncertainty as the norm, constrain outputs with prompts, constrain facts with retrieval, constrain actions with function calling, constrain integration with standard protocols, and pin the whole system to an operable track with evaluation and auditing. Both Baidu AI Cloud and general industry engineering practices support this layered approach, and teams can use it to build their own controllable LLM applications from scratch.