Optimizing Large Language Models for AI Agents: Training, Architecture, and Evaluation Practices

    This article outlines practical approaches to optimizing large language models for AI agent scenarios, where tasks span multiple steps, tools, and interruptions. It covers why general-purpose models struggle with instruction decay, unstable tool calls, long-horizon context loss, and security gaps; how to restructure training data around real workflows and failure branches; asynchronous agent reinforcement learning and extreme long-sequence training; sparse mixture-of-experts architectures for balancing capacity and cost; the capabilities agents actually need; a three-layer evaluation system; and engineering recommendations for running agents reliably in production.

    1. Why General-Purpose LLMs Struggle in Agent Scenarios

    Over the past two years, AI agents have moved from demos into real production environments, and the shape of their tasks has changed fundamentally: from “one question, one answer” to long-running execution that is multi-step, cross-tool, and interruptible/resumable. In this setting, the shortcomings of general-purpose LLMs become concentrated and concrete.

    1. Instruction decay: As the number of turns grows, early constraints are gradually forgotten, and the model starts drifting away from the intended goal.
    2. Unstable tool calls: Parameter hallucination, wrong call ordering, and no self-correction after failures.
    3. Long-horizon breakage: Tasks can span tens of minutes or even hours; once the context exceeds the window, state is lost.
    4. Security gaps: External tools introduce permission sprawl and prompt injection risk.

    Therefore, optimizing models for agent scenarios cannot be a matter of patching the inference side alone. It requires systematic rework across training data construction, optimization objective design, and architecture choices.

    2. Core Training-Side Changes: Exposing the Model to Real Workflows

    2.1 Building Training Corpora from Real Task Distributions

    Traditional pretraining corpora are mostly static text and lack the closed loop of “state—action—observation.” The agent-oriented approach organizes training samples as trajectories:

    1. Task: Generate a weekly report and archive it
    2. Step 1: tool_call(calendar.query, {range: "this week"})
    3. Observation: [meeting list]
    4. Step 2: tool_call(doc.create, {...})
    5. Observation: created_id=xxx
    6. Step 3: verify(created_id)
    7. Final: status report

    The key point is covering failure branches: retry and fallback paths for tool timeouts, empty returns, and insufficient permissions must be explicitly included in the training set. Otherwise, in real environments the model will only ever “keep going down one path.”

    2.2 Asynchronous Agent Reinforcement Learning

    Synchronous sampling lets slow tools drag down overall throughput. The idea behind asynchronous reinforcement learning is to decouple sampling from parameter updates: multiple agent replicas interact with the environment in parallel, and once experience is returned, the advantage function is computed centrally and the policy is updated. Three engineering concerns matter:

    • Staleness control: Bound the version gap between samples and the current policy to avoid divergence during training.
    • Reward shaping: Combine “task completion,” “tool call validity rate,” and “step redundancy” into a composite reward.
    • Long-sequence truncation strategy: Perform segmented credit assignment over ultra-long trajectories spanning thousands of messages.

    2.3 Extreme Long-Sequence Training

    To let the model handle thousands of messages in a single run, an explicit long-sequence training stage is needed, combined with positional encoding extrapolation, attention implementation optimization, and gradient checkpointing, so the context window reaches the hundred-thousand-token scale while the maximum output length remains large enough to support long reports and code generation.

    3. Architecture Choices: Sparsity to Balance Capacity and Cost

    A high-capacity model is unacceptable in inference cost if all parameters are activated. The mainstream industry approach is a sparse mixture-of-experts architecture: total parameters can reach the hundreds of billions, while activated parameters per token are only in the billions. Combined with a routing design of dozens of layers and hundreds of experts, this balances quality against throughput.

    Illustrative configuration (describing the general shape only):

    1. model:
    2. total_params: ~700B scale
    3. activated_params: 40B scale
    4. layers: 80
    5. experts: 256
    6. routing: top-k sparse
    7. context:
    8. window: 200K tokens
    9. max_output: 128K tokens

    Note that the gains from a sparse architecture depend on routing load balance; if hot experts concentrate, actual throughput degrades, so training typically introduces an auxiliary load-balancing loss.

    4. Capability Dimensions: What Agents Actually Need

    • Tool calling: Distinguish built-in functions from external skill plugins, describe parameters uniformly with structured schemas, and apply schema validation and failure rollback.
    • Instruction following: Inject system-level constraints through a high-priority channel, and measure constraint retention separately during evaluation.
    • Scheduled and persistent tasks: The model needs state-management semantics for “wait—wake—continue,” working with an external scheduler to guarantee idempotency.
    • High-throughput long chains: Stability takes priority over single-step optimality; local retries are allowed, but global convergence is required.

    5. Evaluation: From Single-Point Scores to End-to-End Pass Rates

    Single-turn Q&A scores cannot reflect agent capability. A three-layer evaluation is recommended:

    1. Capability layer: tool call accuracy, instruction retention rate, structured output validity rate.
    2. Process layer: end-to-end task pass rate, average number of steps, failure recovery rate.
    3. Cost layer: token consumption per task, latency distribution P50/P95.

    Only by observing all three layers together can you locate whether the problem lies in the model, the orchestration, or the environment.

    6. Engineering Recommendations

    • Isolate agent runtime environments in a container platform, apply least privilege to tool permissions, and audit everything end to end.
    • Use logging services and monitoring alerts to keep full traces of trajectories for replay and debugging.
    • In long-context scenarios, use object storage for external memory to avoid unbounded context growth.
    • On the enterprise side, unify key and data boundary management to prevent privilege escalation caused by prompt injection.

    7. Conclusion

    Optimizing models for agent scenarios is essentially about locking “uncertainty” inside an engineering cage: stay close to real workflows during training, use sparsity to balance cost and capacity at the architecture level, and fall back on orchestration, validation, and observability at inference time. Baidu AI Cloud continues to invest in these general capabilities and can provide developers with a composable stack spanning model services, containers, storage, and monitoring, helping agent applications move reliably into production.