Building LLM Applications: From Prompt Engineering to Agent Practice

    This article explains how to build production-grade applications on top of large language models, covering the full stack from model capabilities to governance. It walks through model selection and underlying mechanisms, local versus service-based deployment, prompt engineering techniques, retrieval-augmented generation, agent and tool-calling design, and fine-tuning, evaluation and security. Practical steps, code examples and evaluation metrics are included to help developers move from small, verifiable prototypes to stable, controllable systems.

    1. From Model Capability to Application System

    Building an LLM application is not simply calling a text-generation endpoint. It means combining model capability with data, tools, business processes and safety mechanisms to form a software system that runs sustainably. A complete LLM application usually has the following layers:

    1. Model layer: understands input, generates text, extracts information, writes code or performs reasoning.
    2. Prompt layer: uses system instructions, task descriptions, context and output constraints to guide the model toward stable results.
    3. Data layer: supplies business documents, structured data, historical records and real-time information.
    4. Tool layer: connects to search, databases, compute services, business APIs and file-processing capabilities.
    5. Orchestration layer: decides how tasks are split, when tools are called and how multi-turn interaction proceeds.
    6. Governance layer: handles permissions, logging, content safety, quality evaluation and cost control.

    The focus of application development is therefore not making a single answer “look smart,” but keeping the system accurate, controllable, traceable and maintainable in real business use.

    2. How LLMs Work and How to Choose One

    2.1 Input, Inference and Output

    User input is usually split into tokens. The model computes a probability distribution over the next content based on context, then generates output step by step. A model’s effective context length, generation speed, reasoning ability and knowledge coverage all directly shape application design.

    In engineering practice, it helps to separate these task types:

    • Generation tasks: writing text, summarizing material, drafting proposals;
    • Understanding tasks: classification, extraction, matching and intent recognition;
    • Reasoning tasks: multi-step analysis, conditional judgment and complex decisions;
    • Tool tasks: calling external systems based on user needs;
    • Knowledge Q&A tasks: answering questions from private enterprise material.

    Different tasks do not necessarily require the same model or the same prompting style. Simple classification can use a lightweight model, while complex reasoning needs stronger reasoning ability. For time-sensitive scenarios, you must combine external retrieval rather than relying entirely on static knowledge in the model’s parameters.

    2.2 Mixture of Experts and Reasoning Enhancement

    Some LLMs use a mixture-of-experts architecture that activates only part of the expert networks on each computation, controlling compute cost while keeping a large parameter count. Developers do not need to modify the model structure directly, but they should understand how this affects deployment: parameter scale, memory footprint, concurrency capacity and quantization method are all related.

    Reasoning-enhanced models usually perform more thorough intermediate analysis on complex problems. When designing applications, avoid asking the model to output its entire internal reasoning. Instead, ask for the necessary conclusions, supporting evidence, a summary of steps and verifiable results. This improves readability, helps protect sensitive information and reduces output length.

    3. Local and Service-Based Deployment

    3.1 Why Localize

    Local deployment suits the following scenarios:

    • Enterprise data should not leave the internal network;
    • You need independent control over the model, logs and knowledge base;
    • The application needs low latency or continuous offline operation;
    • You want to adapt, quantize or deeply debug the model;
    • You need to manage multiple internal applications in one place.

    Local deployment does not automatically mean lower cost. The team must take on hardware procurement, model storage, service monitoring, version upgrades, failure recovery and security protection. Before deploying, assess data sensitivity, access volume, response latency and operational capability.

    3.2 A Standard Deployment Flow

    A general deployment flow can be divided into six steps:

    1. Define the model’s purpose, concurrency and context length;
    2. Assess compute resources, memory, GPU memory and disk space;
    3. Choose the full model or a compressed version;
    4. Start the inference service and run health checks;
    5. Connect to business systems through a unified interface;
    6. Set up monitoring, logging, rate limiting and failover.

    The deployment interface should be decoupled from business code as much as possible. The business layer only cares about message format, returned results and error handling, while the underlying model can be swapped as needed. A simplified call flow looks like this:

    1. def generate_answer(messages, client, model_name):
    2. try:
    3. result = client.generate(
    4. model=model_name,
    5. messages=messages,
    6. temperature=0.2,
    7. max_tokens=1200
    8. )
    9. return result.text
    10. except TimeoutError:
    11. return "Service response timed out, please try again later."
    12. except Exception:
    13. return "The service is temporarily unavailable."

    The parameters above are only general concepts; actual configuration should follow the model service’s interface definition. A production environment should also add request IDs, timeout control, retry strategies and sensitive-information filtering.

    3.3 Performance Optimization

    Common optimization directions include:

    • Using quantization to reduce GPU memory usage;
    • Setting a reasonable maximum output length;
    • Adding caching for repeated questions;
    • Using batching to improve throughput;
    • Splitting and summarizing long documents before the main flow;
    • Moving time-consuming tasks into asynchronous queues;
    • Choosing different models based on task complexity.

    Performance optimization should not look at average response time alone. It should also track time to first token, full response time, concurrency stability, error rate and resource utilization.

    4. Prompt Engineering: Getting Stable Results

    4.1 Basic Components of a Prompt

    A high-quality prompt usually contains these parts:

    • Role: the identity the model should work as;
    • Goal: the task to be completed;
    • Background: the necessary business context;
    • Input: the data to be processed;
    • Constraints: what must not be done and which rules to follow;
    • Output format: the required fixed structure;
    • Examples: ideal input and output.

    For instance, an information-extraction prompt can be designed as:

    1. You are a contract information review assistant.
    2. Task:
    3. Extract the contract ID, signing date, payment term and breach clause from the given text.
    4. Requirements:
    5. 1. Use only information that explicitly appears in the source text;
    6. 2. For fields that cannot be found, fill in "Not mentioned";
    7. 3. Do not add or guess;
    8. 4. Output according to the specified JSON structure.
    9. Output format:
    10. {
    11. "contract_id": "",
    12. "sign_date": "",
    13. "payment_term": "",
    14. "breach_clause": ""
    15. }

    This is more stable than “please analyze this contract,” because the model clearly knows the task boundary and the result format.

    4.2 Task Decomposition and Structured Output

    Complex tasks should be split into stages. For example, customer-service handling can be broken into:

    1. Identify the user’s intent;
    2. Decide whether a lookup is needed;
    3. Retrieve relevant content;
    4. Generate candidate answers;
    5. Check whether the answer complies with policy;
    6. Return the final result.

    For structured output, use fixed fields, enumerated values and clear default rules wherever possible. If a downstream program needs to parse the result, it cannot rely only on a natural-language description; add format validation and a retry mechanism for failures.

    4.3 Prompting Principles for Reasoning Tasks

    Reasoning tasks should be given a clear question, boundaries and evaluation criteria, without piling on irrelevant background. You can ask the model to first list the key conditions, then give a conclusion with brief evidence, but do not force it to expose unnecessary internal thinking.

    Prompts should also avoid self-contradiction. Requiring “must explain in detail” on one hand while restricting “do not output any analysis” on the other leads to unstable results. Write a prompt like you design a program interface: reduce ambiguity and make the input-output contract explicit.

    5. Knowledge-Base Augmentation and Retrieval-Augmented Generation

    When a question involves internal enterprise policies, product manuals or real-time material, the model alone is often not enough. The basic flow of retrieval-augmented generation is:

    1. Import documents;
    2. Clean titles, tables and paragraphs;
    3. Split documents into appropriately sized chunks;
    4. Generate vector representations for the chunks;
    5. Store them in a vector index;
    6. Recall relevant chunks based on the user’s question;
    7. Pass the chunks together with the question to the model;
    8. Generate an answer with supporting evidence.

    Document splitting should not mechanically cut at a fixed character count. Try to keep complete relationships between title and body, question and answer, clause and condition. Recall count is not “more is better” either; too much content dilutes the key points and increases the context burden.

    Knowledge-base Q&A also needs to handle these issues:

    • Document version conflicts;
    • Different visibility caused by different permissions;
    • Table and image information that is hard to parse directly;
    • Inaccurate recall for similar questions;
    • The model citing material that does not exist.

    The system should therefore store each document’s source, update time and permission label, and require the model to state clearly when it cannot find evidence rather than fabricate an answer.

    6. Agent Design and Tool Calling

    An agent can be understood as an application that senses a task, plans steps, calls tools and continues based on results. It is not simply adding one “smart” prompt; it needs explicit state management and execution boundaries.

    A practical agent usually includes:

    • A task analyzer;
    • A tool registry;
    • A parameter validator;
    • An executor;
    • A result observer;
    • Memory or state storage;
    • An exception-handling module.

    Tool descriptions should be concise and accurate, with clear parameter types and usage conditions. For example:

    1. {
    2. "name": "query_order",
    3. "description": "Query order status by order ID",
    4. "parameters": {
    5. "order_id": "string"
    6. }
    7. }

    When an agent runs, it should follow the principle of “judge first, then call, then verify.” For high-risk operations such as payment, deletion, publishing or permission changes, add human confirmation or a second check; the model must not execute them directly.

    7. Fine-Tuning, Evaluation and Security Governance

    When prompts and the knowledge base still cannot meet requirements, consider model adaptation. Fine-tuning suits changing output style, task format and domain-specific expression. It is not a replacement for a real-time database, nor a way to load in frequently changing business material.

    Training data should be de-identified, de-duplicated and quality-reviewed, then divided into training, validation and test sets. Evaluation metrics can include:

    • Factual accuracy;
    • Format compliance rate;
    • Task completion rate;
    • Retrieval hit rate;
    • Refusal accuracy;
    • Average response latency;
    • Resource cost per request.

    On security, focus on preventing prompt injection, unauthorized access, sensitive-information leakage, mistaken tool calls and malicious file input. The system should enforce least privilege, run content detection on model output and record the full call chain for auditing and troubleshooting.

    8. Approaches to Real-World Deployment

    In education, you can build course Q&A, homework grading and study-plan generation systems, but keep a teacher-review step and avoid using the model’s judgment directly as a final grade.

    In e-commerce, you can build shopping-guide and customer-service assistants using a product database, inventory API and after-sales rules. The model handles user intent, while the business system provides real inventory, prices and order status.

    In internal office scenarios, you can build policy Q&A, meeting minutes, report generation and process assistants. The key for such systems is not language expression but permission isolation, cited evidence and process traceability.

    Conclusion

    Building LLM applications is a systems-engineering effort. Prompts determine interaction quality, the knowledge base addresses information freshness, tool calling extends execution capability, service-based deployment ensures stable operation, and evaluation and governance decide whether the system can truly reach production. Developers should start from small, low-risk scenarios, first establish a verifiable minimal closed loop, then gradually add data integration, automated processes and agent capabilities, finally forming a stable, controllable intelligent application with ongoing optimization.