Large Language Models and AI Agents: A Practical Guide to Production Deployment

    This guide explains why large language models and AI agents are increasingly delivered together, and how to build a reliable agent system. It covers a five-layer decoupled architecture, modeling agents as finite state machines instead of long prompts, tool-calling and structured output conventions, retrieval-augmented generation for time-sensitive knowledge, a three-tier evaluation system, observability and cost control, least-privilege security and compliance, and a staged rollout path from a single closed-loop scenario to cross-system automation.

    1. The Trend: Why Models and Agents Are Becoming Bound Together

    A clear pattern has emerged in the industry recently: a cloud vendor released an AI agent product for office scenarios at the same time as a large model capability update. The signal is that plain “model API calls” are giving way to a combined delivery model of “model + agent.”

    The reason is straightforward. A model provides general reasoning and generation capability, but what the business actually needs is to get the work done. Agents fill exactly that gap: they interpret the goal, break it into steps, call tools, verify results, and retry or fall back on failure. The model is the engine; the agent is the transmission and control system. Neither one alone produces a deliverable product experience.

    For developers, this means a shift in where the capability boundary sits. We used to optimize single-turn answer accuracy; now we have to design for composite metrics such as task completion rate, average number of steps, tool call success rate, and human takeover rate.

    2. Overall Architecture: Layered Decoupling Is the Key

    A robust agent system is best split into five layers, with explicit contracts between them, so that prompts, business logic, and infrastructure are not coupled together.

    1. Access layer: a unified entry point for authentication, rate limiting, quotas, and auditing that hides differences between backend models.
    2. Orchestration layer: task planning, state machine transitions, tool selection, and retry strategy.
    3. Capability layer: model inference, retrieval augmentation, structured output, and content safety filtering.
    4. Tool layer: adapters for business systems such as ticketing, calendar, documents, databases, and notifications.
    5. Observability layer: logs, metrics, distributed tracing, and evaluation sample collection.

    The direct benefit of this layering is replaceability: models can be rolled out gradually, tools can evolve independently, and evaluations can be replayed offline, so switching one model does not force a rewrite of the entire pipeline.

    3. Agent Orchestration: From Prompts to State Machines

    The early approach was to stuff every requirement into one long prompt. That works in demos but quickly gets out of control in production. A more engineering-oriented option is to model the agent as a finite state machine.

    1. # Minimal skeleton of a task state machine
    2. class AgentState:
    3. def __init__(self, goal):
    4. self.goal = goal
    5. self.plan = [] # planned steps
    6. self.step = 0
    7. self.context = {} # intermediate results
    8. self.retry = 0
    9. def run(state: AgentState, tools, model, max_steps=8):
    10. while state.step < max_steps:
    11. action = model.decide(state.goal, state.plan, state.context, tools)
    12. if action.type == "call_tool":
    13. result = tools[action.name](**action.args)
    14. state.context[action.key] = result
    15. elif action.type == "finish":
    16. return action.answer
    17. state.step += 1
    18. state.retry = 0 if action.ok else state.retry + 1
    19. return fallback(state)

    Three points matter here. First, planning and execution are separated, so a plan can be reviewed by a human. Second, tool calls must be structured, with arguments validated against a schema. Third, there must be upper bounds on steps and retries to avoid infinite loops that drive costs out of control.

    4. Tool Calling and Structured Output Conventions

    Tools are the only channel through which an agent reaches real business systems, and they are also where most failures concentrate. The following conventions are recommended:

    • Every tool should have a defined input schema, output schema, and error codes, with argument validation on the tool side rather than the model side.
    • Write operations must be idempotent, deduplicated with a business-side unique key, so model retries cannot create duplicate orders or duplicate notifications.
    • High-risk actions should use a two-phase “propose - confirm - execute” flow, with a second confirmation from a human or a policy engine.
    • Prefer constrained generation for structured output, and fall back to a retry rather than guessing when parsing fails.
    1. {
    2. "tool": "create_ticket",
    3. "args": {"title": "Expense claim missing invoice", "priority": "P2"},
    4. "idempotency_key": "req-8f21c"
    5. }

    5. Retrieval Augmentation and Knowledge Freshness

    Office scenarios demand high freshness, since policies, templates, and processes change at any time. Hard-coding knowledge into model parameters is neither economical nor reliable; retrieval augmentation is the more realistic choice. Documents are chunked into a vector index, retrieval results carry their source and version number, and answers must cite where they came from.

    A few engineering details matter: chunk granularity affects recall quality; metadata (department, effective date, classification level) determines filtering capability; and reranking can significantly improve Top-K quality. Knowledge updates should go through incremental sync with version records, which makes issue tracing easier.

    6. Evaluation: Turning “Feels Good” into Numbers

    An agent without evaluation cannot be iterated. Three tiers are recommended:

    1. Offline test sets: covering typical tasks, boundary inputs, and adversarial samples, run as regression on every change.
    2. Online gradual rollout: comparing task completion rate, average steps, latency, and human takeover rate on a small traffic share.
    3. Human spot checks: sampling high-risk scenarios for review and labeling error types (planning error, tool error, hallucination, format error).

    Evaluation results must be traceable to a specific stage, so distributed tracing has to record a summary of the input at each step, tool return codes, and elapsed time.

    7. Observability and Cost Control

    Agent pipelines are long and make many calls, so cost and latency can easily get out of hand. Practical measures include: setting a maximum step count and timeout per task; semantic caching for repeated requests; model tiering for subtasks a smaller model can handle; summary compression for long contexts; and trimming tool results before they enter the context.

    For monitoring, at minimum cover task success rate, average cost per task, the distribution of tool error rates, context length percentiles, queue backlog, and the number of times rate limiting is triggered. General-purpose capabilities such as the logging service, monitoring and alerting, message queue, and container platform offered by Baidu AI Cloud can serve as infrastructure options for carrying these metrics.

    8. Security, Permissions, and Compliance

    An agent that can call tools effectively holds the corresponding permissions, so it must be designed on the least-privilege principle: tool credentials issued short-lived and scoped to the task; sensitive data masked before it enters the model; audit records retained across the full pipeline, including who triggered which action and when; and prompt injection handled through input isolation and instruction priority constraints, so content from external documents is not executed as instructions.

    9. A Suggested Rollout Path

    First, pick one high-frequency, low-risk scenario with verifiable results and close the loop there. Second, build the tool contracts and evaluation sets before discussing model upgrades. Third, gradually introduce planning capability and multi-tool coordination. Fourth, complete the gradual rollout, rollback, and human takeover mechanisms, then extend to cross-system process automation.

    The binding of models and agents is not a marketing concept but an inevitability of the delivery format: what users buy is completeness, not a single inference. Make orchestration, tools, evaluation, and governance solid, and every improvement in model capability can genuinely convert into incremental business value.