Building AI Agents on LLMs: A Practical Engineering Guide for Production

    This article breaks down how to package large language model capabilities into reliable, orchestrated, and testable AI agent systems. It covers a four-layer architecture, task planning strategies, tool-calling safeguards, context management, evaluation and regression, progressive rollout, and common anti-patterns to avoid.

    1. Why LLMs and Agents Are Now Delivered Together

    A clear signal has emerged in the industry: a cloud vendor released a new LLM version and, at the same time, launched an agent product for office scenarios. This is not a coincidence but a predictable outcome of maturing technology and business demand.

    Over the past two years, teams typically validated a model’s core capabilities first and only later considered how to turn them into an application. Today, model vendors and platform providers increasingly deliver “model + orchestration framework + tool ecosystem + evaluation system” as a single package. There are three reasons:

    1. Capabilities are shifting outward: Relying only on model parameters and context windows can no longer cover real business needs. External capabilities such as retrieval, computation, and system calls are required to fill the gaps.
    2. Delivery costs are falling: Infrastructure such as agent orchestration, tool registration, and observability is becoming standardized, pushing the industry from “model as a service” toward “model as productivity.”
    3. User expectations have changed: Enterprise users are no longer satisfied with chat-style Q&A. They expect end-to-end completion of a document, a data reconciliation, or an approval workflow.

    This article therefore does not focus on any specific model or product. Instead, it frames the topic as a general engineering problem: how to reliably package LLM capabilities into an agent system that is orchestratable, testable, and operable.

    2. Overall Architecture: Four Layers from Model to Agent

    A production-ready agent system is usually divided into four layers. The purpose of this separation is to decouple components that change at different rates, so that a model upgrade does not disrupt the entire business logic.

    • Model layer: Handles understanding, reasoning, and generation. Focus areas include context length, structured output stability, call latency, and concurrency quotas.
    • Capability layer: Atomic tools such as retrieval services, database queries, computation engines, file processing, and message notifications.
    • Orchestration layer: Responsible for task planning, tool selection, loop control, termination decisions, and state management.
    • Governance layer: Covers permissions, auditing, logging, monitoring and alerting, cost tracking, and evaluation regression.

    The orchestration layer is what distinguishes an agent from a simple Q&A system. It turns “a single generation” into “multi-step execution,” which also introduces new problems such as loops, retry on failure, and context bloat.

    3. Task Decomposition and Planning: Making the Model Think Before It Acts

    The most common failure mode is handing a complex task to the model in one shot. The reliable approach is explicit planning.

    There are three common strategies:

    • One-shot planning: The model first outputs a complete list of steps and then executes them one by one. It is controllable, but the plan can go off track when initial information is insufficient.
    • Rolling planning: Remaining steps are re-evaluated after each step is executed. It is flexible but requires strict limits on step count and budget.
    • Hierarchical planning: An upper layer defines goals and sub-goals, and a lower layer performs local planning for each sub-goal. It suits long office workflows.

    A sample planning output can be constrained to a structured format for program validation:

    1. {
    2. "goal": "Organize quarterly sales data and generate a brief",
    3. "steps": [
    4. {"id": 1, "action": "query_sales", "args": {"quarter": "Q3"}},
    5. {"id": 2, "action": "aggregate", "args": {"by": "region"}},
    6. {"id": 3, "action": "render_doc", "args": {"template": "brief"}}
    7. ],
    8. "max_steps": 12
    9. }

    In practice, it is recommended to set limits on max_steps, per-step timeout, and total token budget at the same time. When any one of them is reached, the system should enter a fallback path rather than loop indefinitely.

    4. Tool Calling: The Real Source of Stability

    Tool calling amplifies an agent’s capabilities and is also the main source of failures. A stable tool layer should follow a few principles:

    1. Clear descriptions: Tool names, purposes, parameter meanings, and return structures must be accurately understood by the model. Ambiguous descriptions lead directly to incorrect calls.
    2. Strong parameter validation: Model-generated arguments are untrusted and must be validated for type, range, enum values, and permissions before execution.
    3. Idempotent design: Write operations should support idempotency keys to avoid duplicate submissions caused by retries.
    4. Readable errors: Error messages should distinguish “retryable” from “requires parameter changes” and be returned to the model for self-correction.
    5. Least privilege: Each tool should be granted only the minimum data scope required for the current task.

    A simplified example of tool registration and validation:

    1. from dataclasses import dataclass
    2. from typing import Callable, Dict, Any
    3. @dataclass
    4. class Tool:
    5. name: str
    6. description: str
    7. schema: Dict[str, Any]
    8. handler: Callable[..., Any]
    9. idempotent: bool = False
    10. def safe_invoke(tool: Tool, args: Dict[str, Any]) -> Dict[str, Any]:
    11. if not validate(tool.schema, args): # strong parameter validation
    12. return {"ok": False, "reason": "invalid_args"}
    13. try:
    14. result = tool.handler(**args)
    15. return {"ok": True, "data": result}
    16. except RetryableError as e:
    17. return {"ok": False, "reason": "retryable", "detail": str(e)}
    18. except Exception as e:
    19. return {"ok": False, "reason": "fatal", "detail": str(e)}

    5. Context Governance: Controlling Bloat and Information Pollution

    Multi-step execution causes context to expand quickly, driving up costs and diluting attention. Practical governance measures include:

    • Layered memory: Keep the current sub-task context in short-term memory, store historical conclusions as summaries in mid-term memory, and retrieve them on demand from long-term memory.
    • Structured handoff: Pass structured results between steps instead of long natural-language text to reduce redundancy.
    • Pre-retrieval filtering: Apply relevance and permission filtering before feeding content into the context to avoid interference from irrelevant material.
    • Explicit forgetting: Proactively remove outdated or overturned conclusions to prevent the model from building on wrong premises.

    It is worth noting that more context is not always better. In practice, the negative impact of noisy information on generation quality is often greater than that of insufficient information.

    6. Evaluation and Regression: Turning “Looks Usable” into “Measurable”

    Evaluation of an agent system must cover three dimensions:

    • Result correctness: Whether the final answer meets business rules, verified by a combination of rule checks and manual sampling.
    • Process soundness: Whether steps are redundant, exceed permissions, or take detours, analyzed through trajectory logs.
    • Stability: The success rate and variance of repeated runs on the same input, reflecting whether the system can be relied on.

    It is advisable to maintain a fixed set of test cases, run automatic regression when the model or prompts change, and set threshold alerts on key metrics. An agent without a regression mechanism turns every adjustment into a gamble.

    7. Rollout Strategy: Canary Release, Observability, and Cost Control

    Production deployment should follow a gradual path:

    1. Shadow running: The new version only logs and does not execute, comparing differences against the old version.
    2. Small-traffic canary: Roll out by user or scenario, observing success rate and human takeover rate.
    3. Full release: Use monitoring, alerting, and automatic rollback as a safety net.

    Observability should cover at least call-chain tracing, per-step latency, tool failure rate, token consumption, and the number of human interventions. For cost control, smaller models or cached results can be used for low-risk steps, reserving high-value reasoning for the main model.

    8. Common Anti-Patterns

    • Pursuing full automation without human confirmation points, causing errors to be amplified in execution.
    • Vague tool descriptions that make the model repeatedly trial and error, lengthening and destabilizing the chain.
    • Evaluating only the final answer while ignoring process-level permission violations and data leakage risks.
    • No budget limits, allowing abnormal inputs to trigger long loops and runaway costs.
    • Treating prompts as the only maintenance point, with no version management or regression.

    9. Conclusion

    Delivering models and agents together is essentially delivering “capability” and “usability” as one. For development teams, the real competitive edge lies not in calling a particular model but in possessing a complete engineering capability: task planning, tool governance, context control, evaluation regression, and canary operations. With this chain well built, a single model upgrade can translate smoothly into a business improvement; without it, even the strongest model remains stuck at the demo stage.