LLM Engineering Practice: Agents, Evaluation, and Inference Optimization
This guide explains how to turn language-model capability into a reliable system. It covers agent execution boundaries, domain assistants, multimodal evaluation, padding and position handling in batch generation, KV-cache tradeoffs, and a staged path from correctness checks to performance work.
1. From Model Capability to System Capability
Practical work with large language models usually involves several connected questions: whether the model understands the task, whether it can obtain reliable knowledge, whether it can call external capabilities, and whether it can run stably under real load. These problems cannot be solved only by increasing parameter count. The model, data, retrieval, execution environment, and evaluation mechanisms need to be organized as a complete system.
A language model learns linguistic patterns by predicting what comes next in a sequence. The quality, coverage, and information density of the training corpus affect how well the model handles knowledge, instructions, and complex context. Training performance is not the same as business performance: strong results on general questions do not mean the model understands an organization’s internal rules, and the ability to generate plausible tool-call text does not mean it can safely perform real operations.
Engineering work should therefore distinguish three layers:
- Model layer: semantic understanding, content generation, and task reasoning.
- System layer: knowledge retrieval, tool orchestration, permission checks, and state management.
- Runtime layer: inference scheduling, resource allocation, monitoring and alerting, and failure recovery.
A gap in any layer can prevent a seemingly correct demo from becoming a reliable service. In practice, define the task boundary and acceptance criteria first, then choose the model and deployment approach. Do not select a model first and only later look for an application.
2. Agents: Putting Generation Inside a Verifiable Execution Loop
2.1 Tool Calling Is Not the Same as Autonomous Reliability
An agent can be understood as a system that organizes observation, decision-making, execution, and feedback around a goal. The model proposes the next action, an external program performs the operation, and the result is returned to the model, forming an iterative process.
A basic flow is:
User request → task judgment → action plan → action validation → tool execution → result intake → answer or continue.
What matters most is not whether the model can “think of” an operation, but whether the system can verify that the operation is necessary, permitted, and executable. Looking up a document and changing a business record carry different risks and should not use the same authorization method.
2.2 Define an Explicit Contract for External Operations
Each tool capability should define its input structure, data types, permission scope, and return format. Parameters generated by the model are data awaiting validation, not trusted instructions.
Validation should at least check:
- Whether required parameters are present and correctly typed.
- Whether the target is within the user’s permission scope.
- Whether sensitive data or unauthorized access is involved.
- Whether a write requires human confirmation.
- Whether a failed execution can be retried, and whether a retry could create duplicate results.
Actions that change external state should have idempotency controls, audit records, and compensation where needed. Read operations also need permission checks, because information leakage does not require a data modification.
2.3 Control the Execution Loop and Context Growth
An agent may call several tools in sequence, increasing response time, context length, and operating cost. Set a maximum number of steps, a total timeout, and stop conditions.
History should also be managed in layers: keep the current goal, important constraints, and verified results, and compress low-value intermediate steps. A summary can reduce context use, but it cannot replace original evidence. For critical numbers, permission decisions, or operation results, keep a traceable record.
Instruction-like text in external documents should be treated as content to analyze, not as system instructions. Even if the model misreads its meaning, permission checks and execution rules should continue to apply outside the model.
3. Domain Knowledge Assistants: Decide Whether to Answer First
3.1 Group Conversations Are Harder Than One-to-One Q&A
In a multi-person conversation, a message is not necessarily a question for the assistant. It may be extra context, a citation of someone else’s view, casual chat, or an unfinished discussion. If the assistant answers every message, it can interrupt normal communication and treat a fragment as a complete task.
A group knowledge assistant should first decide whether to intervene, then decide how to answer. Trigger rules can combine explicit questions, mentions, topic relevance, and recent conversation state. When the goal is unclear, ask a follow-up instead of automatically filling in unconfirmed background.
Session isolation matters as well. History from different groups, users, and discussion threads must not be mixed, and internal information from one group must not be used to answer another group.
3.2 Use Retrieval to Extend the Model’s Knowledge Boundary
Domain knowledge often changes frequently and is a good fit for retrieval-augmented generation. The basic process is:
- Clean, split, and index documents.
- Retrieve candidate passages for the question.
- Deduplicate and rank candidates, then check permissions.
- Give the relevant evidence to the model to compose an answer.
- Output source information and any necessary statement of uncertainty.
How documents are split directly affects retrieval quality. Passages that are too small may lose definitions and conditions of use; passages that are too large introduce unrelated content. Prefer splits that follow headings, paragraphs, clauses, and table structure, and keep metadata such as document version, update time, and section location.
3.3 Treat “Cannot Answer” as a Normal Outcome
When retrieval returns nothing, evidence is outdated, or sources contradict each other, do not force the model to produce a definite answer. Return what additional information is needed, state that the current evidence is insufficient, or ask the relevant person to confirm.
Permission filtering should happen before evidence enters the model, not only through redaction in the final answer. Sensitive content that has already entered the context can be reorganized or inferred indirectly.
4. Multimodal Evaluation: Create Reproducible Comparison Conditions
Multimodal models can jointly process inputs such as text and images, but tasks demand very different capabilities. Fluent image descriptions do not mean the model can accurately read small text, and recognizing objects does not mean it understands numerical relationships in a chart.
4.1 Split Capabilities by Business Task
Evaluation should at least distinguish:
- Visual recognition: objects, attributes, and scene judgment.
- Text reading: recognition and semantic understanding of text in images.
- Spatial relations: position, direction, count, and relative relationships.
- Chart analysis: trends, proportions, axes, and numerical comparison.
- Combined reasoning: conclusions drawn from visual evidence and textual conditions.
Do not replace all capability analysis with one aggregate score. For a business use case, stability on a critical task may matter more than the average score across unrelated tasks.
4.2 Fix Input Processing and Generation Conditions
Image scaling, cropping, compression, orientation correction, and how multiple images are arranged can all change the information the model actually receives. Prompt templates, output-length limits, and sampling settings also affect results.
When comparing systems, record these conditions and use a consistent configuration whenever possible. Otherwise, observed differences may come from input processing or inference settings rather than from the model itself.
4.3 Evaluate Quality and Cost Together
Answer accuracy is only one dimension. Online model selection also needs to observe time to first output, full response time, resource use, failure rate, and stability under high concurrency.
Automatic scoring suits standardized tasks, but open-ended answers should also be spot-checked by people. Record failures by category, such as factual errors, missed information, unsupported inference, and noncompliant format, so evaluation results can guide system improvement directly.
Model size and final quality cannot be equated in a simple way. Data quality, visual encoding, training objectives, and the inference implementation all affect results. Different configurations should be compared only when the task is clear and the conditions are the same.
5. Padding in Batch Generation: A Correct Mask Can Still Read the Wrong Position
5.1 Why Padding Is Needed
In batch inference, input lengths usually differ. To form a regular tensor, shorter sequences are padded to a common length for the batch. That process is padding.
Padding positions are not valid semantic content. Systems typically use an attention mask to distinguish real tokens from padding tokens, but the mask does not solve every problem: after the model produces outputs, the correct position’s prediction distribution still has to be selected.
5.2 A Common Error Comes from Choosing the Last Position
In autoregressive generation, the next token is normally taken from the output distribution at the end of the prompt. With right padding, the last array position of a short sequence may be a padding position.
Suppose two inputs are:
Sequence 1: [A, B, C]Sequence 2: [D, E, PAD]
If the generation program always reads the last column, sequence 2 does not read the position corresponding to E. Even if the attention mask prevents the model from attending to the padding key, that output position may still not match what the generation program expects.
Batch generation for some decoder-style models is often better suited to left padding, but that should not be treated as a universal rule. The correct approach is to check the model’s position encoding, mask construction, and generation logic.
5.3 Track Valid Positions Explicitly
With right padding, select the output of the last real token according to the valid length. The logic is:
For each sample in the batch:valid length = number of valid positions in that sample's attention masklast valid position = valid length - 1next-token distribution = output distribution[sample index, last valid position]
This logic assumes that valid tokens are contiguous on the left. For left padding or a more complex layout, compute the real positions instead of applying this pattern directly.
Also check position IDs, stop conditions, and how the mask is updated during generation. If an end token is reused as the padding value, confirm that stop detection can distinguish input padding from a newly generated end token.
Tests should compare single-sequence inference with mixed-length batch inference on the same input. Under deterministic decoding and the same configuration, an unexpected difference often indicates a problem in padding, position IDs, or cache management. Numerical precision and the execution implementation should also be checked.
6. Key-Value Cache: Less Repeated Computation, Not Zero Attention Cost
6.1 Basic Principle
In standard causal attention, each position produces query, key, and value representations. When generating a new token, the model uses the current position’s query to compute relevance against historical keys, then aggregates historical values with those weights.
Recomputing keys and values for every historical position on every new token repeats work. A key-value cache stores the keys and values of historical positions at each layer, so later steps compute representations only for the new position.
This reuse is valid only when the model structure and inference process allow the historical state to remain valid. After the prompt, position configuration, or certain model computation conditions change, the existing cache may no longer be usable.
6.2 Separate Prefill from Step-by-Step Decoding
Inference is usually divided into two stages:
- Prefill: process the input prompt and build the historical cache.
- Decoding: generate new tokens, read the historical cache, and append the current state.
Prefill processes multiple input positions and is usually highly parallel. Decoding generates tokens step by step and is often limited by cache reads and memory bandwidth. A long prompt and a long output therefore create different performance pressure.
The cache avoids recomputing historical state, but a new query still has to interact with the retained historical keys and values. For full attention, a longer cache usually increases the read and compute cost of each step.
6.3 Estimating Cache Size
Cache size can be estimated roughly as:
Cache bytes ≈ 2 × number of layers × batch size × cache length × number of key-value heads × dimension per head × bytes per element.
The factor of 2 corresponds to keys and values. The formula estimates the main data volume and does not include extra overhead such as memory alignment, paging, or temporary buffers. The number of key-value heads should follow the model’s actual structure and should not be replaced by the number of query heads.
In long-context or high-concurrency settings, the cache can become the main resource constraint. Common directions include allocating cache on demand, shortening useless context, using an appropriate precision, and managing the history window when the model supports it. Any change in precision or context range needs quality to be revalidated.
7. Verify Correctness Before Optimizing Performance
A practical plan can proceed in stages:
Stage 1: Define the task. Specify inputs and outputs, knowledge scope, permission requirements, acceptable errors, and response latency. Avoid a vague goal such as “better results.”
Stage 2: Establish a baseline. Use a clear prompt and the fewest components, and keep a reproducible test set covering normal, ambiguous, unauthorized, and abnormal inputs.
Stage 3: Add external capabilities. Introduce retrieval and tool calling gradually. Record inputs, outputs, latency, and failure reasons at each step so failures can be located.
Stage 4: Verify the inference implementation. Check inputs of different lengths, padding methods, batch settings, and whether the cache is enabled. Optimize throughput and resource use only after results match expectations.
Stage 5: Run load tests. Do not look only at average latency. Observe high-percentile latency, queueing, timeouts, and how the system degrades when resources are insufficient.
Stage 6: Keep updating. After documents, models, or prompt configurations change, run regression evaluation. Turn production issues into test cases rather than only patching individual answers.
8. Conclusion
The core challenge of applying large language models is turning language generation into a business process that can be verified and controlled. Agents need explicit execution boundaries. Domain assistants need reliable evidence and rules for when to intervene. Multimodal tasks need fair, reproducible evaluation. Batch inference needs correct handling of padding and positions. A key-value cache requires a tradeoff between speed and capacity.
A reliable technical plan follows a clear path: define the task before checking correctness; establish evidence and permission boundaries before expanding automation; understand the resource bottleneck before optimizing performance. Only when these foundations work together can model capability become stable application value.
