Building Production LLM Applications: Prompt Engineering and Agent Implementation

    This article outlines a practical engineering path for taking large language model applications from model capability to business value. It breaks application development into five layers, explains key model mechanisms such as sparse Mixture-of-Experts activation and reasoning-enhanced inference, and walks through private deployment, performance tuning, prompt engineering, retrieval-augmented generation, tool calling, agents, and fine-tuning boundaries. Developers will find guidance on service packaging, observability, evaluation, and scenario-based implementation across education, e-commerce, and customer support.

    1. Why LLM Application Development Needs a Complete Pipeline

    Many teams struggle with LLM adoption not because the model is weak, but because they lack an engineering pipeline that connects model capability to business value: a model is selected but cannot be deployed, prompts grow long yet produce unstable output, a knowledge base is connected but returns irrelevant answers, and an agent is built but cannot be regression tested.

    To address this, application development should be split into five layers: model foundation, runtime and deployment, interaction and prompting, capability extension, and scenario closure. Each layer has clear inputs, outputs, and acceptance criteria, and layers are decoupled through stable interfaces. This way, upper-layer engineering does not have to be rebuilt every time the model is updated.

    At the architecture level, mainstream open-source LLMs generally follow an “input encoding - backbone network - output decoding - post-processing” structure. Understanding this main path matters because the input side determines how context is organized, the backbone determines parameter scale and compute cost, the output side determines sampling strategy and output structure, and post-processing determines content safety and format constraints. In practice, the controllable engineering levers are mostly concentrated in input organization, sampling parameters, and post-processing validation, rather than the model’s internal weights.

    2. Key Model Mechanisms: Sparse Experts and Reasoning Enhancement

    Two concepts appear frequently in recent model design.

    The first is sparse activation in Mixture-of-Experts (MoE) models: the total parameter count is large, but each token activates only a subset of expert networks, expanding model capacity while keeping inference cost roughly controllable. For application developers, this means “large parameter count” no longer necessarily equals “high latency.” It also means memory usage and routing load do not scale linearly, so capacity planning must be based on measured throughput rather than estimated from parameter count.

    The second is reasoning enhancement and chain-of-thought distillation: allowing a model to work through intermediate reasoning steps before producing an answer can significantly improve accuracy on math, code, and multi-step logic tasks. Distilling this reasoning capability into smaller models makes usable reasoning performance available for on-device or low-cost scenarios. The engineering takeaway is direct: for complex tasks, prompts should not pile on constraints but should define the problem clearly and state acceptance criteria explicitly, leaving “how to think” to the model; for simple tasks, input should be compressed and distractions reduced to avoid unnecessary reasoning overhead and over-generation.

    3. Private Deployment and Performance Tuning

    Private deployment is usually driven by three needs: keeping data within a controlled boundary, predictable invocation cost, and availability in network-restricted environments. The key concern in implementation is not “can it run” but “can it serve reliably.” A recommended sequence is as follows.

    1. Deployment form: single-machine inference services suit validation and small-to-medium concurrency; containerized deployment supports elasticity and canary releases; multi-machine, multi-GPU clusters suit high concurrency and long-context scenarios.
    2. Hardware assessment: first determine concurrency, average input and output length, and time-to-first-token targets, then work backward to memory and compute requirements, avoiding buying hardware before identifying the use case.
    3. Quantization and compression: weight quantization, activation precision adjustment, and cache reuse can reduce memory pressure, but quality regression must be run on business corpora to confirm that accuracy loss is acceptable.
    4. Service packaging: unify authentication, rate limiting, timeout, and retry policies, and wrap the model service behind a standard interface that hides underlying differences.
    5. Observability: connect logging and monitoring with alerting, and build dashboards for time to first token, generation rate, failure rate, and token consumption, establishing dual baselines for capacity and cost.

    Example service invocation wrapper (pseudocode):

    1. def chat(prompt, system=None, temperature=0.3, max_tokens=1024):
    2. payload = build_payload(prompt, system, temperature, max_tokens)
    3. resp = client.post(ENDPOINT, json=payload, timeout=30)
    4. if resp.status_code != 200:
    5. raise ServiceError(resp.text)
    6. return normalize(resp.json())

    4. Prompt Engineering: Turning Requirements into Executable Specifications

    The core of prompt engineering is not phrasing but requirement expression. A maintainable prompt usually contains four parts: role and goal, task breakdown, input/output specification, and exception handling conventions.

    • The system prompt carries long-term stable constraints, such as output language, format, prohibited actions, and fallback strategy; the user prompt carries only variables for the current task. Separating the two makes prompts reusable.
    • Structured input and output are key to stability. Clear hierarchical headings, field names, and examples constrain output far more effectively than stacked adjectives. When necessary, require the model to output a JSON skeleton first and then fill in content, making it easier for programs to parse and validate.
    • For reasoning-enhanced models, simplify input and distill requirements: compress lengthy background into key points and remove task-irrelevant distractions. For general conversational models, strengthen role definition and step breakdown, using explicit workflows to reduce the chance of drifting off task.
    • Prompts should be version controlled, reviewed alongside code, and regression tested with a fixed test set that measures accuracy, format compliance, and refusal rate.

    5. Capability Extension: Plugins, Private Knowledge Bases, and Retrieval Augmentation

    A single model cannot cover real-time data or private domain knowledge, so two types of extension are needed. The first is tool calling: encapsulate retrieval, computation, database queries, ticketing systems, and other functions as tools with clearly defined parameters, let the model decide when to call them, and have the application side handle permissions and result validation. The second is retrieval-augmented generation (RAG): document parsing - chunking - vectorization - indexing - retrieval - reranking - generation - citation, with every stage measurable. In practice, poor results are usually not a model problem but come from chunks that are too coarse, retrieval without reranking, and answers without citation traceability. It is advisable to require citation snippets in the output and use fallback phrasing for questions without supporting evidence.

    When building a private knowledge base, permission isolation and update mechanisms must be considered at the same time: incremental document updates, expiration and removal of stale content, and filtering retrieval scope by role to prevent unauthorized recall.

    6. The Boundary Between Agents and Fine-Tuning

    Agent = planning + memory + tools + reflection. The design essentials are to break the goal into verifiable subtasks, set a maximum number of steps and termination conditions, retain the execution trace for replay and debugging, and introduce human confirmation for high-risk actions. Fine-tuning should be introduced only after prompt engineering and RAG can no longer solve problems such as consistent style, fixed format, and domain terminology. Parameter-efficient fine-tuning should be preferred, and a separate evaluation set should be prepared to prevent overfitting.

    Education scenarios focus on solution steps and error-cause analysis, e-commerce scenarios focus on product knowledge and multi-turn shopping guidance, and customer service scenarios focus on ticket routing and emotion recognition. All three share the same foundation, with differences reflected in the knowledge base, tool set, and evaluation criteria. With the general capabilities of cloud platforms such as Baidu AI Cloud, engineering closure can be achieved by combining object storage, container platforms, logging services, and monitoring with alerting. Future trends center on multimodal integration, on-device small models, and stronger tool-calling capabilities. The core competitiveness of developers will shift from “knowing how to write prompts” to “knowing how to define problems, design evaluations, and govern cost.”