Building Enterprise AI Agents from Scratch: Architecture, Orchestration, and Production Practices
Learn how to build enterprise AI agents that can execute tasks, recover from failures, and operate within clear security boundaries. This article covers layered architecture, planning, tool contracts, memory, validation, and the evaluation and governance practices needed to move from a prototype to a production system.
As large language models move beyond answering questions to taking action, AI agents are becoming a practical way to apply them to business workflows. An agent must do more than generate text: it needs to plan tasks, call tools, manage state, and complete workflows within defined constraints.
This article takes an engineering approach to building agents that are operable, measurable, and adaptable—not just one-off demos.
1. Define the Problem Before Building the Agent
Treating an agent as “a model that is better at chatting” leads to poor architectural decisions. A more useful definition is:
An agent is a closed-loop system in which a model reasons and makes decisions, tools and the environment execute actions, and an orchestration layer manages state, permissions, and failure recovery under defined goals and constraints.
Its value is not in appearing more human, but in handling three types of work:
- Cross-system orchestration: Managing tickets, approvals, and resource operations.
- Knowledge-intensive decisions: Retrieving information, comparing evidence, and producing traceable conclusions.
- Long-running workflows: Clarifying requirements across multiple turns, executing steps, and writing results back to business systems.
If a deterministic pipeline can reliably complete a task, an agent may be unnecessary. Agents are better suited to tasks with clear goals but uncertain execution paths, where tool combinations and exception handling matter.
Before starting, ask four questions:
- Can success be verified?
- Can tools be invoked safely, and can their changes be rolled back?
- Are failures observable?
- Are human intervention points clearly defined?
Without these foundations, a project can easily become a system that talks convincingly but cannot reliably act.
2. Use a Layered Architecture
Separate reasoning from execution. A five-layer architecture creates clear responsibility boundaries and makes it easier to replace models or add tools.
Interaction Layer
This layer handles conversations, multimodal input, progress updates, and human confirmation. Complex operations require confirmation gates to prevent a single model-generated call from causing an irreversible change.
Reasoning Layer
The language model handles intent recognition, task decomposition, tool selection, and result explanation.
Prompts should define the model’s role, output format, prohibited actions, and when to ask clarifying questions. Clear constraints are more useful than lengthy statements of intent.
Orchestration Layer
This is the engineering core. It manages:
- State machines or graph-based workflows.
- Retries and timeouts.
- Parallel and sequential execution.
- Human approval nodes.
- Conversation-level and task-level memory.
Without orchestration, even a capable model is effectively a stateless function.
Tool Layer
Expose business capabilities through interfaces that are describable, permission-controlled, and auditable. Tools may perform queries, writes, calculations, or notifications.
Each tool needs:
- A natural-language description.
- JSON Schema parameters.
- A defined permission scope.
- An idempotency key.
- A timeout policy and error codes.
Governance Layer
This layer covers logging, tracing, evaluation, quotas, secrets management, content safety, and action auditing. Once an agent can modify data, governance is no longer optional.
For cloud deployments, object storage can hold attachments and execution traces, message queues can support asynchronous long-running tasks, and container platforms can host tool microservices. Logging, monitoring, and alerting should cover the full call chain.
These are general infrastructure capabilities, not dependencies on a particular vendor’s proprietary interfaces. Where available, Baidu AI Cloud model services and retrieval capabilities can also support managed inference and enterprise knowledge augmentation. The priority remains robust tool contracts and orchestration.
3. Core Mechanisms: Planning, Tools, Memory, and Validation
Planning: From Single Actions to Interruptible Plans
Simple tasks can use a reason–act–observe loop. Complex tasks should begin with an executable plan that specifies steps, dependencies, required tools, and success criteria.
Plans must be interruptible. If one step fails, the system should replan the affected portion rather than restart the entire workflow.
A structured plan might look like this:
{"goal": "Generate and submit this week's capacity report","steps": [{"id": "s1", "action": "query_metrics", "need_confirm": false},{"id": "s2", "action": "draft_report", "need_confirm": true}],"stop_conditions": ["missing_permission", "data_incomplete"]}
Success criteria must be machine-checkable, such as required fields being present or thresholds being met. Otherwise, the system cannot reliably determine when to stop.
Tool Calling: Contracts Matter More Than Model Capability
The model selects tools based on their descriptions. Ambiguous descriptions can lead to incorrect API calls.
Practical guidelines include:
- Give each tool one clear responsibility; avoid universal interfaces.
- Use strongly typed parameters and enumerations to limit free-form input.
- Make write operations idempotent by default, using business-level idempotency keys.
- Return machine-readable errors so the agent can distinguish between retrying, selecting another tool, or asking the user for clarification.
- Require explicit confirmation for high-risk tools, showing a summary of the proposed changes.
Tool access must follow the caller’s identity. An operations account and a guest account should not see the same tool set, even when using the same agent.
The orchestration layer must enforce permissions. Instructions asking the model to respect access controls are not sufficient.
Memory: Working, Episodic, and Long-Term
Working memory contains the current task context, including the plan and intermediate results. It needs size limits and a summarization strategy.
Episodic memory stores conversation-level facts, such as user preferences and confirmed constraints.
Long-term memory comes from knowledge bases and business systems. Retrieve relevant information when needed rather than placing the entire knowledge base in the prompt.
Retrieval must include permission filtering and source references. Answers should point to supporting source passages so they can be audited. Timestamps and version information help prevent the agent from confidently relying on outdated knowledge.
Reflection and Self-Validation
Add a validation step before submitting the final result. This can include format checks, a rules engine, and a second model review focused on omissions and unauthorized actions.
If validation fails, return to planning instead of delivering an incorrect result. For numerical checks, permissions, and deletion operations, deterministic rules should take precedence over a model’s judgment.
4. Move from Prototype to Production
Evaluation
Build a task suite that covers:
- Simple question answering.
- Single-tool tasks.
- Tasks with dependencies across multiple tools.
- Adversarial prompts.
- Attempts to exceed permissions.
Evaluate more than response fluency. Track task completion rate, average tool-call count, unauthorized-action rate, human intervention rate, and end-to-end latency.
Run regression tests whenever prompts change or models are replaced. A system that produces better-written responses may still perform worse at completing tasks.
Security
Treat prompt injection, data leakage, and accidental operations as first-class risks.
Keep system instructions separate from untrusted user input. Treat tool outputs as untrusted data when interpreting them. Keep secrets out of the model context, and maintain audit logs for operations.
External web pages and files should be sanitized before entering the context.
Cost and Latency
Use deterministic rules where they are sufficient. Avoid repeated model deliberation when a single retrieval operation can resolve the task.
Run long tasks asynchronously and show stage-by-stage progress in the interface. Cache and reuse results on frequently executed paths.
Human–Agent Collaboration
Production agents generally need humans in the loop:
- Automate low-risk actions.
- Require confirmation for medium-risk actions.
- Route high-risk actions through ticket-based approval workflows.
Write human decisions back in a structured format so they can become useful data for future improvement.
Iteration Strategy
Start with a narrow workflow, such as read-only queries followed by summary generation and human-controlled sending.
Establish observability and permissions before introducing write operations. Capability should grow through broader tool coverage, stricter rules, and more comprehensive evaluation—not indefinitely longer prompts.
5. Common Failure Modes
- No state machine: Multi-turn workflows rely on concatenated conversation history and break down as tasks grow longer.
- Tool descriptions do not match actual interfaces: The model attempts unsupported or incorrectly formed calls.
- All knowledge is placed in the prompt: Costs rise, and permission isolation becomes difficult.
- Only wording is optimized: Task completion and unauthorized-action rates receive too little attention.
- No rollback mechanism: A write succeeds, a later step fails, and the system is left in an inconsistent state.
Address these problems with persistent task-level state, contract tests for tools, permission-aware retrieval, evaluation gates in the release process, and compensating actions for writes.
6. A Practical Starting Checklist
- Define the goal, success criteria, prohibited actions, and human approval gates.
- Identify the minimum tool set and complete its schemas, permissions, idempotency behavior, and error codes.
- Implement a plan–execute–validate loop through orchestration rather than a single generation call.
- Add logging, tracing, and task-level replay.
- Build an evaluation suite from real failures, and require it to pass before expanding into new scenarios.
The strength of an agent lies in placing uncertain reasoning within predictable engineering constraints. With sound architecture, tool contracts, evaluation, and governance, replacing the model can improve reasoning quality without requiring the entire system to be rebuilt.
Without those foundations, even a powerful model remains an expensive chat interface. Progress from a narrow, complete workflow to broader tool and permission coverage, then iterate through evaluation. That is how an agent becomes an operable business system rather than a concept demo.
