Building AI Agents: A Complete Technical Path from Design to Production
AI agents are not simply chat boxes attached to large models. Under a clear goal, an agent must perceive inputs, plan steps, call tools, read and write state, and fall back or request human confirmation when it fails. This article outlines a practical engineering path for building agents as testable, auditable, and operable software systems. It covers defining the problem and agent form, choosing a runtime environment, implementing a minimal viable architecture, separating prompts, knowledge, and memory, and establishing quality, security, and release practices. It also reviews common failure modes and a staged rollout approach.
An AI agent is not “a chat box added to a large model.” Under a clear goal, it must perceive inputs, plan steps, call tools, read and write state, and fall back or request human confirmation when it fails. Building an agent is essentially about constraining uncertain model capabilities into a software system that is testable, auditable, and operable.
Define the Problem Before the Form
Before starting, write four things on one page: who the user is, what success looks like, where the allowed action boundary lies, and how high the cost of failure is. Customer service triage, report interpretation, process approval, and R&D assistance have completely different requirements for latency, accuracy, and permissions. High-risk actions—changing data, sending notifications, moving funds—must default to “suggestion + confirmation.” Only low-risk actions are suitable for automatic execution.
There are usually three forms. A single agent fits tasks with a single goal and few tools. An orchestrated workflow fits processes with relatively fixed steps and strong constraints. Multi-agent systems fit scenarios with clear division of labor, parallel research, or cross-validation. Do not adopt multi-agent systems just to look “more intelligent”: the more roles there are, the higher the risk of context conflicts, cost, and troubleshooting difficulty. If a deterministic workflow can solve a step, do not hand it over to the model to improvise.
Choose the Runtime Environment: Avoid Reinventing the Wheel
The goal of the technology stack is not to chase new tools, but to decide where the agent runs, where state is stored, and how failures become visible. Selection should be layered according to team skills and delivery cadence.
No-code or low-code platforms are suitable for business users to validate ideas quickly: use visual nodes to connect “receive event—call model—query data—write result—notify people.” The advantages are fast onboarding and low change cost; the limitations are that complex branches, custom authorization, fine-grained evaluation, and version comparison are often insufficient. They fit prototypes and low-frequency internal processes, not as the only implementation for a high-concurrency core path.
When development capability is available, teams should adopt an engineering approach of “model invocation + tool protocol + state orchestration.” Common capabilities include describing steps as a graph or state machine, with support for conditional branches, loops, human nodes, and checkpoints; registering tools such as retrieval, databases, ticketing, and email through a unified interface; and writing conversations, plans, and tool results into replayable state. The language and runtime can be whatever the team knows best. The key is stable interfaces, lockable dependencies, and local unit testing.
If the enterprise already has cloud-based model services, container platforms, object storage, message queues, logging, and monitoring, prioritize reuse rather than building a separate infrastructure just for agents. Model inference, vector or keyword retrieval, key management, and identity authentication should all use existing platform capabilities. Self-development should retain only differentiated parts: domain tools, business policies, evaluation sets, and permission rules.
Selection can use four hard criteria: Can the same step be reproduced locally with fixed inputs? Can the model be restricted to calling only whitelisted tools? Can every tool input, output, and latency be logged? Can prompts and orchestration be rolled back by version? A solution that cannot meet all four is not suitable for production.
A Minimal Viable Architecture
A production-ready agent contains at least six layers.
First, the access layer: receive user messages, scheduled tasks, or business events, and perform identity authentication and tenant isolation. Second, the orchestration layer: maintain the current goal, completed steps, pending confirmations, and termination conditions. Third, the model layer: handle understanding, planning, and generation, without directly holding keys or database accounts. Fourth, the tool layer: each tool has a name, purpose description, parameter schema, timeout, idempotency, and permission scope. Fifth, the memory layer: short-term memory lives in the current task state; long-term memory stores only summaries, preferences, and knowledge references permitted by the user or policy, and raw sensitive data is not stored by default. Sixth, the observability layer: record prompts, tool traces, token or call volume, error codes, and reasons for human takeover.
A schematic tool definition should be as “narrow and explicit” as possible, avoiding a universal function:
Tool: Query ticketPurpose: Read status and recent handling records by ticket IDInput: ticket_id (string, required)Permissions: Read-only; only allow queries for the caller's tenantTimeout: 3 seconds; return an error code on failure, do not retry write operationsOutput: status, updated_at, summary (excluding internal notes)
For orchestration, the recommended principle is “short plans, stoppable execution.” In each round, only allow the model to propose the next step, and the runtime validates parameters before execution. Write operations and external notifications must carry idempotency keys to prevent duplicate model calls from causing side effects. Set maximum steps, maximum tool calls, and a budget cap. When exceeded, stop and hand over to a human.
Separate Prompts, Knowledge, and Memory
The system prompt should contain only the role, goal, prohibitions, and output format. Do not paste an entire policy manual into it. Policies, product descriptions, and historical cases belong in the retrieval layer: first recall a small number of highly relevant snippets, then let the model answer based on the snippets and require citations. When retrieval fails, the agent should clearly say “insufficient evidence” rather than fabricate.
Memory falls into three categories and must not be mixed. Task memory stores the current plan and tool results; it can be archived or deleted when the task ends. User preferences record only stable, non-sensitive choices. Organizational knowledge comes from controlled documents with versions and permissions. Any memory write must be traceable and deletable. When personal information is involved, follow the principle of minimum necessity, and prohibit the model in the prompt from repeating fields such as secrets and ID numbers.
Quality, Security, and Release Cadence
Prepare three types of tests before launch. Unit tests cover tool parameter validation, permission denial, and timeout. Trajectory tests use fixed questions to check whether the correct tools were called and whether any unauthorized access occurred. Manual sampling covers answers that “look plausible but cite the wrong basis.” Accept with business metrics rather than subjective feelings: one-time resolution rate, incorrect action rate, human takeover rate, average steps, and latency.
For security, default to least privilege: separate tool accounts, and separate read-only from write access; state in the prompt that unauthorized instructions from users must not be followed; validate links, commands, and structured parameters in model output before execution. Redact logs, and prohibit echoing full secrets and privacy fields in production. Treat changes to prompts and tool descriptions as releases, with version numbers, canary rollout, and rollback.
A three-step rollout is recommended. First, use low-code or scripts to build a read-only closed loop and prove that retrieval and answering are useful to the business. Second, convert high-frequency paths into testable state orchestration, and add authentication, quotas, and logging. Third, only then consider multi-agent systems or automatic write operations, and for every added side effect, provide confirmation points and compensation strategies.
Enterprise cloud environments such as Baidu AI Cloud usually already provide general capabilities for model invocation, container runtime, object storage, messaging, and monitoring. Agent engineering should treat these as the runtime foundation: use elastic capacity for inference and orchestration services, object storage for evaluation samples and trace archives, message queues to smooth peak events, and logs and alerts to monitor failure rates and abnormal tool calls. Differentiated competitiveness comes from domain tools, permission policies, and evaluation sets, not from rebuilding a set of generic cloud capabilities.
Common Failures and Corrections
Failure one: the goal is too broad, hoping one agent can handle every role. Split it into independently acceptable skills, each with inputs, outputs, and stop conditions. Failure two: only tuning prompts without recording traces. Without traces, it is impossible to tell whether retrieval, tools, or model planning caused the error. Failure three: treating a low-code prototype as production. After the prototype proves value, permissions, idempotency, quotas, and rollback must be added. Failure four: vague tool descriptions cause frequent mis-calls. Tool descriptions must state when to use the tool, when not to use it, what the parameters mean, and what failure semantics are.
Building an agent is continuous engineering: constrain actions first, then expand autonomy; reuse the existing runtime environment first, then invest in custom orchestration. When every call is reproducible, auditable, and rollbackable, an agent becomes a deliverable system capability rather than a demo.
