LLM-Native Applications and Agent Systems: Architecture, Prompting, RAG, Tools, and Evaluation

    This article outlines engineering practices for building LLM-native applications and agent systems. It covers layered application architecture, model invocation, prompt design, task decomposition, tool use, retrieval-augmented generation, financial information analysis pipelines, inference optimization, fine-tuning and distillation, safety in medical consultation, multi-agent systems, and quality evaluation. Readers will learn how to combine probabilistic model capabilities with deterministic software engineering, data governance, security controls, and continuous testing to build stable, explainable, and maintainable intelligent applications.

    1. From Model Calls to LLM-Native Application Development

    LLM application development is not equivalent to making a single text-generation API call. A system that can actually be deployed must address model capability, business workflows, data security, tool collaboration, context management, quality evaluation, and runtime cost at the same time. An “LLM-native application” embeds the model’s understanding, reasoning, generation, planning, and collaboration capabilities into business processes and software systems. The model is no longer just a question-and-answer window; it becomes an intelligent component that can perceive tasks, create plans, call tools, and return results.

    A complete application usually contains the following layers:

    1. Interaction layer: Receives user input, displays model output, and handles streaming responses, conversation history, and error messages.
    2. Orchestration layer: Determines task types, decomposes complex problems, and selects appropriate tools or knowledge sources.
    3. Model layer: Provides text understanding, content generation, structured output, and reasoning capabilities.
    4. Tool layer: Connects to databases, retrieval systems, business APIs, compute services, and file-processing capabilities.
    5. Data and governance layer: Handles knowledge management, permission control, log auditing, quality evaluation, and cost accounting.

    In engineering practice, define the business goal first, then decide on model size and system architecture. Do not assign every task to the model simply because it has strong language capabilities. For deterministic tasks such as amount calculation, inventory lookup, identity verification, and permission checks, program logic or business systems should be used first. Models are better suited to natural language understanding, intent recognition, information extraction, task planning, and result explanation.

    2. Development Environment and Model Invocation Basics

    Before building an LLM application, prepare the runtime environment, key management, request wrappers, logging, and test data. Keys should not be written directly into source code. They should be injected through environment variables or a secure configuration center. The application should also set timeouts, retry policies, concurrency limits, and output length limits to prevent resource exhaustion caused by network fluctuations or abnormal input.

    A generic invocation flow can be abstracted as follows:

    1. def invoke_model(messages, model_config):
    2. request = {
    3. "messages": messages,
    4. "temperature": model_config.temperature,
    5. "max_output_tokens": model_config.max_output_tokens
    6. }
    7. response = send_request(request, timeout=30)
    8. result = parse_response(response)
    9. record_log(
    10. input_messages=messages,
    11. output=result,
    12. request_id=response.request_id
    13. )
    14. return result

    In a real system, the returned result also needs format validation. For example, when the model is required to output a structured object, check required fields, field types, and enum values. For content that does not conform to the expected format, limited correction retries can be used, but requests must not be repeated indefinitely.

    Model invocation should be observable. At a minimum, record the following information:

    • Request time, response time, and request identifier;
    • Input length, output length, and estimated cost;
    • Model version or configuration version;
    • Whether tool invocation was triggered;
    • Whether timeout, retry, or format errors occurred;
    • User feedback and the final business outcome.

    This data is used not only for troubleshooting, but also for prompt iteration, model evaluation, and cost optimization.

    3. Prompt Engineering: From Describing Requirements to Constraining Behavior

    A prompt is not simply a “question sentence.” It is a comprehensive description of the model’s role, task objective, input data, processing flow, output format, and constraints. High-quality prompts should reduce ambiguity and explicitly state unacceptable behavior.

    A relatively complete prompt structure includes:

    • Role definition: Explains the model’s responsibilities and professional boundaries;
    • Task objective: Clarifies what work needs to be completed;
    • Input description: Explains field meanings, data sources, and possible missing values;
    • Processing rules: Specifies analysis steps, judgment criteria, and priorities;
    • Output constraints: Specifies format, language, length, and field structure;
    • Error handling: Explains how to respond when information is insufficient, conflicting, or out of scope;
    • Safety boundaries: Prohibits fabricating facts, leaking privacy, or performing unauthorized operations.

    For example, an information extraction task can require the model to return the following structure:

    1. {
    2. "entities": [],
    3. "events": [],
    4. "risk_level": "low|medium|high",
    5. "evidence": [],
    6. "uncertainties": []
    7. }

    It is important to note that prompts cannot replace business validation. Risk levels, amounts, dates, and identity information output by the model should be verified again on the program side. For high-risk scenarios, use a combination of “model triage + rule review + human confirmation.”

    4. Reasoning Capabilities and Task Decomposition

    Complex tasks often cannot be completed through a single generation. Applications can decompose problems into several verifiable steps. For example, financial information analysis can be divided into information collection, source cleaning, event extraction, impact analysis, and report generation. Intelligent medical consultation can be divided into symptom collection, risk identification, follow-up suggestions, and care guidance.

    The key to task decomposition is not to require the model to output lengthy internal reasoning, but to let the system obtain inspectable intermediate results. A structured plan is recommended, for example:

    1. Task objective: Generate an industry trend analysis report
    2. Step 1: Extract event subjects, times, and event types
    3. Step 2: Assess information sources and credibility
    4. Step 3: Analyze business areas that may be affected
    5. Step 4: List uncertainties and information to be verified
    6. Step 5: Generate an evidence-based summary

    For high-risk domains, model-generated content should not be treated directly as a conclusion. The system should retain references, evidence snippets, and the mapping between evidence and model judgments so that users can trace the basis for results.

    5. Agent Architecture and Tool Invocation

    The core of an agent is not “automatic chatting.” It is about giving the model bounded capabilities for perception, planning, action, and feedback. A typical agent loop is as follows:

    1. Receive the task and identify the objective;
    2. Determine whether external data or tools are needed;
    3. Select tools and generate parameters;
    4. Execute tool calls;
    5. Read tool results and decide whether to continue;
    6. Summarize results and output the final response.

    Tool definitions must be clear, including tool name, purpose, parameter types, required fields, and error return format. Too many tools increase the difficulty of model selection, so tools should be grouped by business domain and the range of tools available in a single call should be limited.

    Tool invocation must have safety boundaries:

    • Query operations can be executed automatically;
    • Operations such as writes, deletions, transfers, and message sending should require secondary confirmation;
    • Data involving personal privacy should be redacted and subject to permission checks;
    • Tool parameters should be checked against whitelists, and the model should be prohibited from directly concatenating dangerous commands;
    • Set limits on call count, execution time, and returned data size.

    Protocol-based tool integration reduces system coupling and creates a unified interface between the model and external capabilities. Whether connecting to a database, retrieval service, or business system, a consistent description method should be used, and permissions, versions, and error handling should be standardized.

    6. Retrieval-Augmented Generation and Knowledge Base Construction

    When questions depend on internal enterprise materials, policy documents, product manuals, or real-time information, relying only on knowledge stored in model parameters is usually insufficient. Retrieval-augmented generation provides relevant content to the model as context through a “retrieve first, generate later” approach.

    Knowledge base construction generally includes:

    1. Document collection and format parsing;
    2. Cleaning headers, footers, duplicate content, and invalid characters;
    3. Splitting text by headings, paragraphs, and semantic boundaries;
    4. Adding metadata such as source, time, and permissions to chunks;
    5. Building a vector index or keyword index;
    6. Retrieving relevant chunks based on the query;
    7. Ranking and deduplicating candidate content;
    8. Injecting evidence into the prompt and generating an answer.

    Chunks that are too large may reduce retrieval precision, while chunks that are too small may lose context. In practice, adjust chunking based on document types, query patterns, and evaluation results. For time-sensitive knowledge, add time filtering during retrieval and establish update and invalidation mechanisms.

    During answer generation, the model should be required to distinguish among three cases: “explicitly stated in the material,” “inferred from the material,” and “cannot be confirmed with the current material,” thereby reducing the risk of fabrication.

    7. Engineering Design for a Financial Information Analysis Platform

    Financial information analysis is a typical multi-step task. The system can obtain public information through scheduled collection or event triggers. After deduplication, cleaning, and classification, the model extracts subjects, events, times, impact scope, and potential risks.

    A pipeline architecture is recommended:

    1. Information collection
    2. ↓
    3. Content cleaning and deduplication
    4. ↓
    5. Entity and event extraction
    6. ↓
    7. Combined rule-based and model analysis
    8. ↓
    9. Risk grading and evidence linking
    10. ↓
    11. Report generation and human review

    For any output involving investment decisions, the system should clearly state its information sources, generation time, and uncertainties, and avoid presenting model results as deterministic advice. The system should also retain original text and intermediate results for auditing and traceability.

    8. Model Inference Optimization

    LLM inference optimization usually focuses on caching, attention computation, expert routing, batching, and output control.

    KV cache can reuse intermediate results from context that has already been processed, reducing repeated computation. It is suitable for multi-turn conversations and long-prompt scenarios. However, caching must consider session isolation, expiration time, and privacy security.

    Low-rank attention mechanisms reduce the computation and memory pressure of long-context processing by compressing some intermediate representations. Their effectiveness depends on the implementation, sequence length, and hardware environment, and they cannot be compared simplistically without considering the specific task.

    Mixture-of-experts architectures route different inputs to a subset of expert modules, reducing per-inference activation computation while maintaining a large parameter capacity. However, expert load imbalance, routing stability, and communication overhead still require close attention.

    Multi-step prediction and batching can reduce scheduling overhead during generation and are suitable for scenarios with high throughput requirements. During optimization, evaluate latency, throughput, memory usage, and output quality together rather than focusing on a single metric.

    9. Fine-Tuning, Distillation, and Post-Training

    When a general model cannot reliably complete a specialized task, fine-tuning can be considered. Before fine-tuning, first confirm whether the problem can be solved through prompts, retrieval, or tool invocation, because fine-tuning increases the cost of data preparation, training, and version management.

    Training data should have the following characteristics:

    • Highly relevant to the target task;
    • Clear boundaries between inputs and outputs;
    • Consistent and reviewable annotations;
    • Coverage of normal, abnormal, and edge cases;
    • No unauthorized sensitive information.

    Distillation transfers the behavioral capabilities of a larger model to a smaller model. Common approaches include generating high-quality examples, filtering effective samples, and then using them to train a lightweight model. Distillation does not mean simply copying answers; attention must also be paid to format compliance, error patterns, and task generalization.

    Post-training methods can optimize model behavior through reward signals so that it better aligns with task objectives. Reward design must avoid encouraging only surface-level format while ignoring factual accuracy, safety, and business effectiveness. For complex tasks, rewards can combine metrics such as correctness, completeness, citation quality, response efficiency, and risk control.

    10. Safety Practices for Intelligent Medical Consultation

    An intelligent consultation system can handle symptom collection, information organization, general health guidance, and triage, but it should not replace professional diagnosis. The system should first identify emergency risks, such as severe breathing difficulty, altered consciousness, or persistent severe pain, and prioritize prompting users to seek professional help promptly.

    The consultation flow can be designed as follows:

    1. Collect basic information and main symptoms;
    2. Ask about duration, progression, and accompanying symptoms;
    3. Identify possible high-risk signals;
    4. Output information that requires further confirmation;
    5. Provide non-diagnostic health guidance;
    6. Clarify care channels and urgency levels.

    Medical scenarios must strengthen privacy protection, human review, and disclaimer management. Model output should avoid absolute wording and should not recommend specific drugs or treatment plans without supporting evidence.

    11. Multi-Agent Systems and Enterprise Deployment

    Multi-agent systems are suitable for complex tasks that require collaboration among multiple specialized roles. For example, one agent can handle retrieval, one can perform data analysis, one can generate responses, and another can perform quality checks. Agents should exchange task status through clear message structures rather than relying on free-form natural language communication.

    System design should clarify:

    • The responsibility boundaries of each agent;
    • Task assignment and termination conditions;
    • Shared context and private context;
    • Tool permissions and data access scope;
    • Failure retry and human takeover mechanisms;
    • Full-chain logging and result evaluation methods.

    More agents are not always better. Too many roles increase communication costs and the probability of error propagation. Prefer a small number of components with clear responsibilities, and validate collaboration benefits with test data.

    12. Quality Evaluation and Continuous Iteration

    Before an LLM system goes live, build an evaluation set that covers functionality, effectiveness, safety, and stability. Evaluation metrics can include factual accuracy, structured output pass rate, retrieval hit rate, tool call success rate, correct refusal rate, average response time, and unit task cost.

    Evaluation should not focus only on average scores; it should also examine edge cases and failure cases. Every change to prompts, model configuration, knowledge base, or tool versions should trigger regression testing. For online systems, establish a user feedback loop and classify low-quality answers as knowledge gaps, unclear prompts, tool errors, permission issues, or insufficient model capability, then select targeted improvement plans.

    Overall, LLM-native application and agent development is a systems engineering effort. The model is only one core capability. Application quality is also determined by task boundaries, data governance, tool design, process orchestration, safety mechanisms, and continuous evaluation. Only by combining model capabilities with deterministic software engineering can teams build intelligent applications that are stable, explainable, maintainable, and able to evolve continuously.