How to Build Your Own AI Agent: From Prototype to Enterprise Architecture
Building an AI agent involves more than just creating a chat interface; it requires a robust system capable of executing tasks within controlled boundaries. This article explores the complete journey of developing an AI agent, from defining initial goals and building a minimal viable loop to establishing a unified domain model, separating control and execution planes, and managing multiple version tracks. It covers essential architectural patterns such as layered dependencies, core identifier systems, and dual aggregate roots, along with best practices for knowledge retrieval, tool execution, security, and cost management. Finally, it provides a phased approach to scaling your AI agent from a personal prototype to a reusable enterprise platform.
1. Define the Goal: Chat Window or Task Execution System?
The most common pitfall when building an AI agent is mistaking the ability to “answer questions” for the ability to “complete tasks.”
A chat window primarily solves information exchange; an agent must understand goals within a controlled scope, acquire context, call tools, and advance the task based on execution results. Its value lies not in longer replies, but in converting user intent into verifiable results.
For example, an assistant for R&D and operations might need to complete the following process:
- Understand the abnormal phenomenon described by the user.
- Retrieve relevant operational documentation.
- Query permitted runtime metrics.
- Summarize possible causes and evidence.
- Propose remediation suggestions.
- Execute restricted operations upon authorization.
- Leave a complete operational log.
This involves knowledge Q&A, tool invocation, process control, and permission verification. Therefore, before building, you should define three boundaries:
- Task boundary: What the agent needs to accomplish and what it is not responsible for.
- Permission boundary: What information can be read and what operations require approval.
- Completion boundary: The conditions used to determine whether a task is successful, failed, or requires human intervention.
A personal knowledge assistant can start with “answers must cite source materials,” while an enterprise troubleshooting assistant needs further rules like “can only access resources the current user is authorized for” and “any modification operation must be confirmed.”
This step determines the subsequent architectural complexity. There’s no need to build a complete enterprise platform for a personal document assistant upfront, nor should a simple dialogue script directly undertake high-risk production operations.
2. Minimum Viable Loop: Complete One Task Fully First
A working agent requires at least six basic capabilities:
| Capability | Main Responsibility | Common Risks |
|---|---|---|
| Model Invocation | Understand requests, generate answers, or propose tool calls | Uncertain output, cost overrun |
| Context Management | Organize historical messages, task goals, and necessary materials | Information omission, sensitive data leakage |
| Knowledge Retrieval | Obtain relevant documents and sources | Outdated materials, inaccurate citations |
| Tool Execution | Query data or execute operations | Unauthorized access, duplicate execution |
| Task Control | Manage steps, stop conditions, and manual confirmation | Infinite loops, state confusion |
| Execution Logging | Save processes, results, and usage metrics | Inability to audit or troubleshoot |
It is recommended to choose a low-risk scenario first, such as “answering policy questions based on internal documents,” and then add a read-only tool, like querying the current status of a task.
Do not let the agent operate multiple systems simultaneously at the very beginning. First, verify if the following closed loop holds:
User asks a question -> System authenticates -> Retrieves necessary context -> Calls model -> Validates tool request -> Executes tool -> Returns result -> Saves log.
This chain looks simple, but it covers the most critical engineering problems of an agent system. The fact that a model can generate a correct tool call does not mean the system can skip parameter validation; a successful tool return does not mean the user has received an understandable, traceable answer.
3. Unified Domain Model: Don’t Let Feature Tags Become Entity Boundaries
As usage scenarios increase, the same assistant might appear simultaneously on web pages, business system sidebars, open APIs, and smart programming environments.
If every new entry point duplicates a set of agent configurations, permission rules, and publishing processes, the platform will soon face four types of problems:
- Prompt modifications need to be synchronized in multiple places.
- Different entry points use different knowledge versions.
- Inconsistent tool permission judgments.
- Usage metrics cannot be aggregated under the same business object.
A more robust design is to separate “what the agent is” from “where the agent is called from.”
3.1 Agents are Combinations of Capabilities, Not Mutually Exclusive Types
It is not advisable to rigidly classify agents into mutually exclusive categories like “chat type,” “retrieval type,” or “process type.” Real tasks usually span these capabilities.
You can model an agent as a unified definition object containing:
- Name, purpose, and owner.
- Instructions and output constraints.
- Model usage policy.
- Knowledge sources and retrieval strategy.
- Allowed tool set.
- Execution flow and stop conditions.
- Permission, budget, and risk policies.
Here is an illustration of a custom structure, not representing any existing product interface:
AgentDefinitionidpurposeinstructionmodelPolicyknowledgeBindingstoolBindingsexecutionPolicyaccessPolicybudgetPolicy
Here, knowledge retrieval, process orchestration, and tool invocation are composable capabilities, not isolated product entities.
For smaller systems, these configurations can be saved in a single structured file; as team collaboration and audit requirements grow, they can be gradually split into independent entities.
3.2 Access Methods Modeled Independently
Web chat, business system embedding, programmatic calls, and local development environment access are essentially different interaction adapters.
Adapters are responsible for handling:
- User identity and credentials.
- Input format conversion.
- Page or business context extraction.
- Streaming result delivery.
- Cancellation, reconnection, and exception feedback.
It should not possess another set of agent business rules.
For example, a business page can automatically carry an application ID and a ticket number, but this data is just context to be verified, not direct access permission. The execution plane must still determine whether the user can view corresponding resources based on their real identity.
4. Separate Control Plane and Execution Plane: Configuration Changes Should Not Affect Task Stability
The control plane manages definitions, approvals, publishing, and governance; the execution plane receives requests, organizes context, and calls models and tools.
The core goal of separating the two is to prevent backend administrative activities from directly interfering with running tasks.
4.1 What Should the Control Plane Manage?
The control plane typically includes:
- Agent configuration editing.
- Tool registration and authorization.
- Knowledge source management.
- Version release and rollback.
- User, organization, and role management.
- Evaluation results and runtime reports.
4.2 What Should the Execution Plane Depend On?
The execution plane should read published configuration snapshots, not continuously query editable drafts at runtime.
Once a task starts, its configuration must be fixed. Otherwise, if an administrator modifies tool parameters or instructions halfway through the task, subsequent steps might use different rules than the previous ones, leading to unexplainable results.
For enterprise scenarios, the control plane and execution plane can be deployed as independent processes or services to separately control resources, scaling, and fault impact scopes. A personal prototype can be deployed in a single process first, but with clear module boundaries.
Physical separation is not the first step for all projects, but it is a solution worth evaluating early in high-concurrency, multi-tenant, and strict governance scenarios.
5. Establish Three Version Tracks to Avoid “Re-releasing Everything for One Change”
Agent systems have at least three different types of changes, which cannot be covered by a single version number.
5.1 Platform Runtime Version
This track manages changes to the execution engine, interface adapters, authentication logic, and runtime infrastructure.
For example, adding task cancellation capabilities, adjusting timeout mechanisms, or fixing execution state machine errors belong to platform versions.
Its release focus is compatibility, stability, and fault rollback.
5.2 Agent Definition Version
This track manages instructions, model policies, tool bindings, flows, and budget rules.
On the same platform version, multiple agent definition versions can run simultaneously. New versions should undergo offline evaluation first, then gradually roll out by user, organization, or business scenario.
Published versions should remain immutable. If issues are found, publish a new version or switch back to an old one; do not directly modify historical versions.
5.3 Knowledge and External Contract Version
This track manages knowledge snapshots, index building results, and tool input/output contracts.
Knowledge documents might change daily, while agent instructions do not need to be republished daily. When a tool contract undergoes incompatible changes, the binding relationship should also be explicitly upgraded, rather than letting the original call fail silently.
The three tracks can evolve independently, but must generate a consistent binding snapshot at runtime:
Runtime SnapshotPlatform compatible versionAgent definition versionKnowledge snapshot identifierTool contract version setPermission policy version
Note that recording versions does not mean answers can be perfectly reproduced. Model outputs are non-deterministic, and external system states change. Version snapshots are mainly used to explain configuration context and locate issues; if stronger retrospective capabilities are needed, key inputs and tool result summaries should be saved according to compliance requirements.
6. Six-Layer Directed Acyclic Dependency: Prevent Business Rules from Being Hijacked by Frameworks
To prevent entry points, models, and storage implementations from permeating each other, code responsibilities can be divided into six layers:
- Domain Layer: Defines agents, runtime states, permission rules, and business constraints.
- Application Layer: Organizes use cases like publishing, starting tasks, and resuming tasks.
- Interface Contract Layer: Defines abstract interfaces for model calls, tool execution, storage, etc.
- Infrastructure Adapter Layer: Implements model access, database read/write, and message passing.
- Access Layer: Handles web requests, program calls, and external events.
- Bootstrapping Layer: Creates concrete implementations, completes configuration, and dependency injection.
This does not require six directories to mechanically depend top-down, but requires forming a directed acyclic dependency graph and adhering to dependency inversion:
- The domain layer does not reference external frameworks.
- The application layer uses external capabilities through abstract interfaces.
- The infrastructure layer implements these interfaces.
- The access layer calls application use cases.
- The bootstrapping layer selects concrete implementations.
For example, if the application layer needs to “execute a tool,” it should not directly depend on a specific network client:
Interface ToolExecutorexecute(context, toolName, validatedArguments)Application Use CaseValidate identity and authorizationValidate tool parametersCall ToolExecutorRecord execution result
The “zero-framework compile gate” can be understood as a continuous integration check: the domain layer and core contract layer can still be independently compiled and tested without importing network frameworks, database drivers, or model clients.
The value of this check is not formal purity, but ensuring that changing access methods, storage implementations, or model adapters does not require rewriting business rules.
7. Five Core Identifiers: Distinguish Conversations, Runs, and Steps
When an agent encounters issues, you often need to answer:
- Which tenant initiated the request?
- Which agent does it correspond to?
- Which conversation does it belong to?
- Which task run is it?
- Which execution step failed?
A practical identifier system is:
| Identifier | Meaning | Main Use |
|---|---|---|
| tenant_id | Tenant or isolated space | Data isolation and resource ownership |
| agent_id | Agent identity | Configuration location and statistics |
| conversation_id | Conversation identity | Historical message association |
| run_id | A single task run | State advancement and version binding |
| step_id | A single execution step | Model call, retrieval, and tool tracing |
These identifiers should not replace each other.
One conversation can contain multiple runs; one run can contain multiple steps. Even if a programmatic call lacks multi-turn natural language dialogue, it should still have a run identifier. For stateless requests, the conversation identifier can be empty; there’s no need to forcefully create a session just for uniform formatting.
Distributed tracing identifiers can serve as auxiliary observation info but should not replace business run identifiers. One business run might span multiple network requests, asynchronous tasks, and tracing segments.
It must also be emphasized: identifiers are only location information, not authorization credentials. Knowing a run ID does not mean you can view the corresponding messages or execution results.
8. Dual Aggregate Roots and State Layering: Don’t Cram All Data into One Table
From a domain modeling perspective, you can organize primary business consistency boundaries using two aggregate roots.
8.1 Agent Definition Aggregate
It maintains agent configurations and publishing rules, including:
- Definition drafts.
- Published versions.
- Capability bindings.
- Publishing validation results.
- Ownership and administrative permissions.
The core constraint is: incomplete or incompatible configurations cannot be published, and published versions cannot be directly modified.
8.2 Run Aggregate
It maintains the state of a single task, including:
- Initiator and runtime snapshot.
- Current state.
- Step execution summary.
- Pending confirmation info.
- Final result and termination reason.
The core constraint is: state transitions must be legal, and no new high-risk operations can continue after cancellation or termination.
Conversations, knowledge documents, and audit logs can be associated entities or independently stored objects; they don’t all need to be loaded into the run aggregate. The aggregate boundary emphasizes transactional consistency, not loading all historical data into memory at once.
Additionally, you should distinguish the following states:
- Persistent state: Published versions, run results, approval records.
- Temporary state: Short-term locks, streaming output buffers, execution leases.
- External facts: Business system data queried by tools.
- Derived state: Statistical reports, retrieval indices, and monitoring views.
Long-term records cannot be saved only in temporary caches; external facts cannot be overwritten by unvalidated model summaries.
9. Knowledge Retrieval and Tool Execution: Govern These Two Links Separately
9.1 Knowledge Retrieval Focuses on “Answer Evidence”
When building a knowledge base, you need to handle document cleaning, logical chunking, source recording, permission filtering, and update mechanisms.
The retrieval link can combine keyword matching, semantic retrieval, and result re-ranking based on scenarios, but should ultimately retain source information. When answering, distinguish between:
- Facts explicitly stated in documents.
- Inferences made based on materials.
- Content that current materials are insufficient to confirm.
Retrieving a relevant text segment does not mean the text is necessarily correct or still valid. Knowledge records should include update times, applicable scopes, and validity statuses.
9.2 Tool Execution Focuses on “Action Authorization”
Tool execution must go through a deterministic validation process:
Identity authentication -> Resource authorization -> Parameter validation -> Risk grading -> Necessary approval -> Execution -> Result logging.
Tool permissions depend on the joint constraints of the caller’s identity, the agent’s authorization scope, and current business policies; they cannot be determined solely by model-generated text.
For write operations, special consideration must be given to idempotency and retries. A network timeout might mean “the operation succeeded, but the response was not delivered.” Retrying directly in this case might cause duplicate submissions.
You can design idempotency keys, execution result queries, and manual confirmation mechanisms based on business needs. For operations involving multiple systems, do not easily claim the ability to automatically roll back; if reliable compensation capabilities are lacking, use step-by-step confirmation and clear failure handling flows.
10. Security and Cost: Budget is Also a Runtime Constraint
Agents interact with user inputs, retrieved documents, and tool return contents, any of which might contain misleading instructions.
Therefore, external content should be treated as data and not automatically upgraded to system rules. Even if the model is induced to propose a dangerous tool call, the execution layer must block it through an independent authorization mechanism.
It is recommended to set the following runtime limits:
- Maximum execution steps.
- Timeout for single model calls and tool calls.
- Usage budget for a single run.
- User or tenant-level concurrency limits.
- Tool call frequency limits.
- High-risk operation approval requirements.
These limits must be enforced by the execution engine, not just written in prompts.
Cost records should also be bound to run identifiers. In addition to model input/output usage, resource consumption like retrieval, tool execution, and storage can be recorded. It is necessary to clarify which are metered values and which are just estimates, avoiding directly adding data from different metrics.
11. Evaluation and Release: Don’t Just Look at Answer Fluency
Before an agent goes live, you should prepare an evaluation set covering real scenarios, rather than just testing a few ideal questions.
At least include:
- Can normal tasks be completed?
- Can it clearly state when materials are insufficient?
- Can unauthorized requests be rejected?
- Can it safely terminate after a tool timeout?
- Can malicious instructions bypass security boundaries?
- Does multi-turn dialogue misuse old context?
- Do high-risk actions correctly trigger approvals?
- Does the new version reduce the quality of original tasks?
Evaluation metrics should cover task completion, factual evidence, tool call correctness, unauthorized access, latency, and resource consumption.
Model auto-evaluation can assist in screening, but permissions, security, and key business results cannot rely solely on model judges. It should combine deterministic checks, manual sampling, and business result verification.
The release process can adopt the path of “offline evaluation -> small-scale trial -> gradual rollout -> continuous observation,” with a rollback plan prepared in advance. Rollback configurations cannot undo external operations that have already occurred, so configuration rollback and business compensation must be designed separately.
12. Recommended Implementation Path: Build Progressively by Complexity
Phase 1: Personal Usability
Select a clear task, connect one model capability, add a small amount of trusted materials, and save conversations and source records. Do not open write operations yet; prioritize verifying actual value.
Phase 2: Small Team Usability
Add unified identity authentication, knowledge access control, tool registration, execution logging, and basic budgets. Allow different entry points to reuse the same agent definition.
Phase 3: Production Usability
Introduce immutable published versions, runtime snapshots, complete state machines, approval mechanisms, idempotency handling, continuous evaluation, and fault alerts.
Phase 4: Platform Reusability
Based on actual scale, split the control plane and execution plane, improve module dependency gates, multi-tenant isolation, version compatibility checks, and unified metering.
The most important principle is: do not implement all complex capabilities in advance, but secure the boundaries that won’t easily change as early as possible.
Building your own AI agent truly requires precipitating not a chat interface, but a stable task execution mechanism. A unified domain model solves capability combination issues, independent version tracks solve evolution issues, clear dependency boundaries solve maintenance issues, and state identifiers and aggregate designs solve consistency and tracing issues. Combined with permissions, evaluation, and observability, the agent can grow from an “occasionally impressive prototype” to a “system that continuously delivers trustworthy results.”
