LLM Architecture and Engineering Practices for Agent Tasks

    This article examines how LLM evaluation is shifting from single-turn Q&A toward task completion, and what that shift means for architecture, training, and systems engineering. It covers sparse Mixture-of-Experts design, long-context and attention optimizations, multimodal input handling, post-training methods for agent capabilities, and evaluation metrics. It also discusses distributed deployment strategies, heterogeneous accelerator adaptation, observability, and a deployment checklist. A representative agent loop is included to illustrate tool-result feedback, error handling, and step limits. The article concludes that teams should optimize end-to-end task completion and cost per unit rather than isolated benchmark scores alone.

    1. Background: From Answering to Completing Tasks

    The focus of LLM evaluation is shifting from single-turn Q&A to task completion. Models built for engineering scenarios need to perform multi-step planning, call external tools, read environment feedback, and continuously correct their actions based on that feedback. These capabilities cannot be obtained by scaling parameter count alone; they also require coordination among training objectives, inference architecture, and system scheduling.

    Evaluation dimensions are changing as well. Basic knowledge Q&A still has reference value, but more attention should be paid to the following metrics:

    • End-to-end completion rate of multi-step tasks;
    • Correctness of parameter formats in tool calls and the ability to recover from errors;
    • Retrieval accuracy and state retention in long contexts;
    • Effective output per unit cost.

    2. Key Architecture Design

    2.1 Sparse Mixture-of-Experts Structure

    Mixture-of-Experts (MoE) models split feed-forward layers into multiple expert subnetworks, and each token is routed to only a few of them. The total parameter count can be large, while a single forward pass activates only a small subset of parameters. This design preserves model capacity while controlling the computation required for each inference.

    From an engineering perspective, three points need attention: first, routing balance, to avoid some experts being overloaded for long periods; second, cross-device communication overhead introduced by expert parallelism; third, fluctuations in expert load under batched inference, which directly affect tail latency.

    2.2 Long Context and Attention Optimization

    The computation and memory footprint of standard self-attention grow quadratically with sequence length. Common industry optimizations include:

    • Sparse attention: computes attention only within local windows or between selected positions;
    • Linear attention: approximates the softmax operation with kernel functions, making complexity approximately linear with sequence length;
    • Hybrid structure: keeps full attention in some layers and uses linear or sliding-window attention in others, trading off quality and efficiency.

    When context is extended to the million-token level, the KV cache becomes the main bottleneck. In practice, this usually requires a combination of KV cache quantization, paged memory management, and scheduling policies that allocate memory according to request priority.

    2.3 Multimodal Input Processing

    When text, images, audio, and video are encoded into the same sequence, tokenization and alignment across modalities must be handled. From an engineering perspective, two things should be distinguished: whether the model can understand multimodal input, and whether the system can process multimodal input reliably. Media file decoding, resolution normalization, and frame sampling strategies all affect latency and cost, and should be standardized in the preprocessing stage.

    3. Training and Evaluation of Agent Capabilities

    Improvements in agent-style models mainly come from the post-training stage. Common approaches include:

    1. Tool-call data: construct function-call samples with parameter schemas, while retaining feedback traces from both successful and failed calls;
    2. Multi-turn environment interaction: execute code in an isolated sandbox, read terminal output, and use verifiable execution results as reward signals;
    3. Rejection sampling: select complete trajectories with correct steps and verifiable results for retraining.

    Evaluation should distinguish three types of metrics. Knowledge metrics measure pure reasoning capability, tool metrics measure call accuracy, and task metrics measure end-to-end completion rate. Relying only on knowledge metrics can underestimate the model’s value in real workflows and misjudge where its limitations lie.

    A typical agent loop structure is as follows:

    1. def run_agent(task, tools, llm, max_steps=20):
    2. history = [{"role": "user", "content": task}]
    3. for _ in range(max_steps):
    4. reply = llm.chat(history, tools=tools)
    5. if not reply.tool_calls:
    6. return reply.content # Model provides the final answer
    7. history.append({"role": "assistant", "content": reply.content or ""})
    8. for call in reply.tool_calls:
    9. try:
    10. result = tools[call.name](**call.arguments)
    11. except Exception as e:
    12. result = f"Tool execution failed: {e}" # Feed error back so the model can correct itself
    13. history.append({"role": "tool", "content": str(result)})
    14. raise RuntimeError("Reached maximum steps without completing the task")

    This code has two key points. First, tool results must be fed back into the context so the model can decide the next step based on real feedback. Second, a step limit and exception branches are essential; otherwise, the loop may continue indefinitely and consume a large amount of compute.

    4. Systems Engineering: Distributed Deployment and Heterogeneous Compute

    4.1 Choosing a Parallelism Strategy

    LLM inference usually requires combining multiple parallelism methods:

    • Tensor parallelism: splits matrix operations within a layer to reduce per-GPU memory usage, but requires low inter-device communication latency;
    • Pipeline parallelism: splits the model by layers, suitable for cross-node deployment, at the cost of pipeline bubbles;
    • Expert parallelism: places different experts on different devices, requiring handling of all-to-all communication overhead.

    In actual deployment, the combination of the three depends on model structure, hardware topology, and request characteristics. It is recommended to first use stress testing to identify bottlenecks, then decide on the parallelism strategy.

    4.2 Heterogeneous Accelerator Adaptation

    When deploying on non-mainstream GPUs or alternative accelerator cards, the main work includes operator replacement and fusion, communication library adaptation, and numerical precision validation. It is recommended to establish a unified operator test set, compare output errors against a reference implementation item by item, and retain a switchable fallback path.

    4.3 Observability

    Production environments should monitor at least the following metrics: time to first token, tokens generated per second, request queue time, tool call failure rate, and cost per task. Logs should record request IDs and step numbers to facilitate replay and reproduction. Alert thresholds need to be set according to business peaks and troughs to avoid frequent false alarms.

    5. Deployment Checklist

    • Define task boundaries: distinguish operations allowed to execute automatically from operations that require human confirmation;
    • Set approval nodes: add confirmation steps for irreversible operations such as writing files, sending messages, and deploying to production;
    • Validate inputs and tool outputs: limit input length and type, and prevent malicious content from spreading through tool results and inducing the model to perform unauthorized operations;
    • Canary release: roll out by task type in batches, and compare changes in completion rate and cost for each batch;
    • Regular regression evaluation: build evaluation sets from real business samples, and compare results before and after version upgrades.

    6. Conclusion

    The transition of LLMs from conversation to execution depends on coordination across architecture efficiency, task-level training, and systems engineering. Engineering teams should use end-to-end task completion rate and cost per unit as core metrics, rather than referring only to individual benchmark scores.