AI Agent Architecture in Practice: What the Agent Race Means for Engineering Teams
As capital and consumer platforms bet on AI agents, the competition is shifting from model benchmarks to whether agents can reliably complete end-to-end tasks. This article breaks down a production-grade agent architecture: defining capability boundaries across read-only, write, and high-risk tiers; orchestrating tool calls with strict schema validation, read-write separation, and idempotency keys; managing context through layered memory and hybrid retrieval with reranking; building an evaluation system that tracks task completion, cost, safety, and stability; and applying least-privilege governance against prompt injection. It also maps these building blocks to general cloud infrastructure and suggests a phased rollout roadmap.
1. Reading the Industry Signals: Capital and Devices Are Both Betting on Agents
Two recent industry developments are worth attention from technical teams. First, an AI company founded only five years ago completed an initial public offering of unprecedented scale, with fundraising that set a historical record. Second, a device manufacturer disclosed in job postings that it is developing a general-purpose agent capable of web browsing, application operation, and code writing, planned for release within the next year, to compete head-on with existing personal assistant products in the market.
On the surface, both are capital and product news. In essence, they point to the same technical judgment: the supply of large model capability is already relatively sufficient, and the focus of competition is shifting from “model metrics” to “whether agents can reliably complete end-to-end tasks.” The pricing logic of capital markets is paying for predictable compute and inference demand; the device manufacturer’s move is a fight for the new entry point of human-computer interaction. For developers and enterprise users, the real opportunity is not chasing any single product, but building agent engineering capability into reusable infrastructure.
A common misconception needs clarification: an agent is not a “bigger model.” It is a combined system of four elements: model, tools, state, and constraints. The model handles decision-making and generation, tools reach the real world, state maintains task continuity, and constraints ensure results stay within bounds. If any element is missing, the system degrades into an unusable demo.
2. Defining Capability Boundaries: Decide What Not to Do First
The first design document for a production-grade agent should specify capability boundaries rather than a feature list. A three-tier breakdown is recommended:
| Tier | Typical Capabilities | Risk Level | Implementation Advice |
|---|---|---|---|
| Read-only | Retrieval, queries, summarization, code explanation | Low | Can be fully automated |
| Write | Creating tickets, modifying configurations, submitting code | Medium | Requires secondary confirmation and a rollback plan |
| High-risk | Deleting data, changing permissions, external publishing | High | Mandatory human approval and two-person review |
Once boundaries are set, they must be enforced in three places simultaneously: the prompt, the tool whitelist, and gateway policies. This avoids troubleshooting costs caused by inconsistencies such as “the prompt allows it but the gateway blocks it.”
3. Tool Call Orchestration: Keeping Uncertainty in a Cage
Tool calling is the part of an agent most prone to losing control. The recommended engineering structure is a three-stage flow: intent parsing, argument filling, and execution validation.
# Illustrative code: minimal safeguard structure for tool callsfrom dataclasses import dataclassfrom typing import Callable@dataclassclass ToolSpec:name: strschema: dict # JSON Schema for arguments, used to constrain model outputhandler: Callable # actual execution logicread_only: bool = Truedef invoke(spec: ToolSpec, raw_args: dict, approved: bool = False):# 1. Argument validation: reject anything that does not match the schema; no "good-faith guessing"if not validate(raw_args, spec.schema):raise ValueError(f"invalid arguments for {spec.name}")# 2. Permission check: write operations require explicit approvalif not spec.read_only and not approved:raise PermissionError("write operation requires approval")# 3. Idempotency control: the caller passes an idempotency key to avoid duplicate submissionsreturn spec.handler(raw_args)
Three points deserve emphasis. First, argument validation must fail hard. If hallucinated arguments from the model are “auto-corrected,” errors propagate silently to downstream systems. Second, read-write separation is the most effective risk control: read-only tools can be called freely, while write tools must go through an approval chain. Third, the idempotency key is generated and persisted on the business side and reused on retries, which prevents duplicate orders and duplicate resource creation.
4. Context and Memory Management: Balancing Cost and Quality
The context window is a limited resource and a major cost driver. The mature approach is layered memory:
- Working memory: tool results for the current task, stored in structured form and released when the task ends;
- Session memory: multi-turn summaries instead of stacking raw text, keeping token growth under control;
- Long-term memory: extracted into entities and preferences, stored in a database, and retrieved and injected on demand.
For the retrieval-augmentation step, the common pattern is “hybrid recall plus reranking”: keyword recall and vector recall run in parallel, then a reranking model scores everything together. An illustrative flow:
User request→ Query rewriting (resolve references, decompose sub-questions)→ Hybrid recall (keyword + vector, TopK from each)→ Reranking (unified scoring, truncate noise)→ Context assembly (system constraints + long-term memory + fragments + tool list)→ Model decision
Assembly order affects output quality: placing strong constraints first and volatile data last is usually more stable than random concatenation.
5. Evaluation: No Evaluation, No Iteration
Agent evaluation must go beyond “is the answer correct” and cover four dimensions:
- Task completion rate: whether the end-to-end goal is achieved;
- Steps and cost: the number of tool calls and token volume consumed for the same task;
- Safety: whether privilege escalation occurs or sensitive information is leaked;
- Stability: variance across multiple runs with the same input.
A dual-track mechanism of an offline evaluation set and online canary release is recommended. The offline set covers typical scenarios and long-tail anomalies, and a regression run is triggered every time the prompt, model, or tool description changes. Online traffic is canaried by percentage, with monitoring and alerts watching failure rates and latency percentiles. Teams without a regression set can hardly tell whether an “optimization” is an improvement or a regression.
6. Security and Governance: Least Privilege by Default
Because agents can operate real systems, governance requirements are higher than for ordinary applications:
- Credentials are managed by a key management service and must never be written into prompts or code repositories;
- All tool calls are logged, with logs desensitized before entering the logging service for audit and traceability;
- A policy engine is placed in front of sensitive operations, making dynamic decisions by role, environment, and data classification;
- An output filtering layer blocks prompt injection and data exfiltration.
Prompt injection is the most realistic threat: web pages, documents, and code comments can all carry malicious instructions. The defense principle is to treat all external content as data rather than instructions, and to enforce explicit separation of instructions and data at the system level.
7. Implementation on Baidu AI Cloud: Combining General Capabilities
The architecture above maps directly onto general cloud product categories without relying on any proprietary interface: a container platform hosts agent services and the tool gateway with elastic scaling; object storage holds evaluation sets and raw knowledge base files; a message queue smooths traffic spikes and enables long-running tasks to run asynchronously; logging and monitoring with alerting form the observability foundation; and key management plus access control secure credentials and permissions. Baidu AI Cloud provides exactly this kind of general infrastructure capability, which teams can combine freely according to their own tech stack, avoiding lock-in to a single framework.
8. Suggested Evolution Roadmap
- Phase 1 (1–2 months): a single-scenario read-only agent, connecting the tool gateway and the evaluation set;
- Phase 2 (3–4 months): introduce write operations and an approval flow, completing idempotency and rollback;
- Phase 3 (5–6 months): multi-agent division of labor, separating planning from execution, and establishing a cost dashboard;
- Ongoing: drive iteration with the evaluation set, and tighten permission and cost baselines quarterly.
Capital enthusiasm and device competition will change, but the fundamentals of agent engineering are a long-term asset: clear capability boundaries, strict tool constraints, a regression-capable evaluation system, and a least-privilege governance framework. Get these four things solid, and the system can migrate smoothly and keep producing business value no matter how the underlying models are replaced.
