Learning AI Agent Architecture: A Practical Guide to Multi-Role Customization
Learn how to build learning AI agents with a unified execution core, layered memory, governed skills, and offline evaluation. This guide covers coding, research, and design role configuration, access isolation, reliable continuous operation, and staged implementation criteria—while distinguishing memory and skill updates from model training.
1. From Conversation to Sustained Task Execution
When building AI agents, developers often focus first on model capability and tool availability. In real workflows, however, the most persistent problems are often about continuity rather than answer quality: requirements confirmed earlier must be explained again, solved problems are repeatedly investigated, shared context causes interference between roles, and interrupted long-running tasks are difficult to resume.
Learning agents connect task execution, knowledge retention, and performance evaluation. Beyond handling the current request, they can turn useful experience into information that supports future work, subject to explicit permissions and governance rules.
“Learning” needs to be distinguished at three levels:
- Memory updates: Retaining confirmed preferences, facts, constraints, and task state.
- Skill development: Organizing repeatable methods into procedures with defined conditions of use.
- Model parameter training: Adjusting model weights through a separate training process that requires additional data, compute, and evaluation.
The first two can usually be implemented without changing model parameters. Remembering a user preference or adding an operating guide does not mean the underlying model has been trained. This distinction is essential to understanding agent capabilities accurately.
2. Build a Unified Execution Core Before Adding Interfaces
2.1 Different Interfaces Should Not Mean Different Execution Logic
An agent may receive requests through a terminal, web interface, messaging channel, development environment, or scheduled task. If each interface separately implements prompt assembly, memory retrieval, and tool invocation, behavior can become inconsistent. One interface may enforce permissions while another bypasses them; one may persist task state while another supports only one-off conversations.
A better architecture treats interfaces as adapters and centralizes execution in a unified core:
Terminal / Web / Messaging Channels / Scheduled Tasks↓Authentication and Request Normalization↓Agent Execution Core↓Context Management → Reasoning and Decisions → Tool Execution↓State Storage, Audit Logs, Skill Retrieval
Adapters handle message format conversion, identity mapping, and result delivery. The execution core handles decisions, state management, and tool authorization. This reduces duplicate implementation work and makes centralized testing easier.
A unified core does not imply globally shared state. Multiple roles can reuse the same execution code while maintaining separate configurations, workspaces, and access boundaries.
2.2 The Core Loop Must Support Stopping and Recovery
Agents commonly use a reasoning–action–observation loop: the model analyzes a task, proposes a tool call, the system executes it, and the result is returned to the model for the next decision.
The following pseudocode illustrates the architecture; it does not represent an actual framework API:
Load task stateRead memory and skills within the authorized scopeRepeat:Check cancellation signals, deadlines, and resource budgetsAssemble the current contextObtain the model's next decisionIf the task is complete:Save the result and task stateExit the loopValidate the tool name, arguments, and invocation permissionsRequest human confirmation when requiredExecute the tool and record its resultUpdate task state
Reliability depends on the control conditions inside this loop. The system should limit execution rounds, tool calls, individual call duration, and the total task budget to prevent repeated, unproductive attempts.
Cancellation must also extend beyond a button in the interface. Interrupting a model request does not necessarily stop an external operation that has already started. The tool execution layer therefore needs its own lifecycle management. Operations that cannot be safely canceled must have their final status explicitly recorded.
3. Manage Context with Layered Memory, Not an Endless Chat History
3.1 Working Memory: Support the Current Task
Working memory holds recent conversation, temporary information needed for reasoning, tool results, and pending actions. It changes frequently and is time-sensitive, so it should not automatically become a source of long-term facts.
When context approaches its capacity limit, earlier conversation can be compressed. The summary should prioritize:
- The current objective and acceptance criteria.
- Constraints already confirmed by the user.
- Important actions already performed.
- Unresolved questions.
- References needed to locate files, tasks, and deliverables.
Compression is not simply shortening text; it is preserving task state. If a summary drops a constraint such as “do not modify production data,” subsequent execution may exceed the original authorization.
3.2 Episodic Memory: Record What Happened
Episodic memory captures the process and outcome of a task, including troubleshooting paths, failure causes, verification methods, and final conclusions.
Records should include timestamps, sources, applicable environments, and outcome status. A successful case demonstrates that a method worked under particular conditions; it does not establish a universal rule.
For example, a record stating that a configuration change restored normal operation should also preserve the conditions before and after the change and the evidence used to verify recovery. It should not be reduced to “change the configuration whenever this problem occurs.”
3.3 Long-Term Facts and Preferences: Retain Stable, Confirmable Information
Long-term memory is appropriate for explicitly stated output preferences, project conventions, and constraints that remain valid over time.
Each record should include information such as:
Record contentAssociated user or projectInformation sourceConfirmation statusCreation timeLast verification timeExpiration date or invalidation conditionsAccess scope
Model inferences should not be treated as user-confirmed facts. A request for a short answer on one occasion does not necessarily mean every future task should receive a short response.
Long-term memory should also support querying, correction, and deletion. When a user withdraws a preference, the system must address related summaries and retrieval copies so that outdated records no longer influence behavior.
3.4 Keep Task State Separate from Knowledge Retrieval
Execution progress, pending approvals, and operation success belong in structured task state. Document content, historical cases, and lessons learned can be loaded as needed through retrieval.
Do not rely on a natural-language summary to determine critical states such as whether a payment has completed or a file has been submitted. Facts involving external side effects should be established through reliable operation records or queries to the external system.
4. Turning Experience into Skills Requires Separate Governance
4.1 A Skill Is a Procedure with Explicit Boundaries
A reusable skill should be more than a prompt such as “check carefully.” It should define a complete execution contract:
- Applicability: Which tasks the skill can handle.
- Input requirements: Required materials and permissions.
- Execution steps: How to carry out the task.
- Verification: How to determine whether it succeeded.
- Failure handling: When to stop, roll back, or escalate to a human.
- Risk disclosure: Which sensitive operations may be involved.
For a bug-fixing skill, for example, the procedure might require reproducing the issue, identifying the smallest necessary change, and running relevant tests. If the issue cannot be reproduced, the agent should report the missing evidence rather than claim that the problem has been fixed.
4.2 Automatic Skill Generation Is Not Automatic Approval
Extracting procedures from task traces can reduce manual documentation work. However, even successful traces may contain incidental steps, environment-specific dependencies, or unsafe actions.
A more reliable process is:
Task Trace↓Candidate Skill Extraction↓Removal of Sensitive Information and Environment-Specific Dependencies↓Permission Checks, Duplicate Detection, and Content Review↓Offline Testing or Human Review↓Versioned Release and Usage Monitoring
Low-risk skills may use a lighter review process. Skills involving bulk deletion, permission changes, external publishing, or sensitive information should face stricter review.
4.3 Skill Pruning Must Preserve Rollback
As a skill library grows, duplicates, conflicts, and outdated content will appear. Governance can identify skills that need attention using usage frequency, the most recent verification date, failure history, and changes in the applicable environment.
Low usage does not imply low value. A disaster recovery procedure may remain important even if it is rarely used. Prefer marking skills as “pending review” or “archived,” while retaining versions and a restoration path, rather than deleting them outright.
5. Validate Improvements with Offline Evaluation
A learning loop should include task execution, experience extraction, candidate changes, evaluation, and controlled release. Without evaluation, the system may simply accumulate content without becoming more reliable.
5.1 Build an Evaluation Set That Reflects Real Tasks
Evaluation tasks should cover:
- Common successful workflows.
- Missing information that requires clarification.
- Tool timeouts, permission denials, and execution failures.
- Requirements that change across multiple turns.
- Malicious instructions embedded in external content.
- High-risk operations that should be refused or escalated.
Evaluation must consider more than the final answer. It should also check compliance with authorization, correct use of evidence, and completion of necessary verification.
5.2 Compare Candidate Procedures Under Controlled Conditions
Different versions of a skill can be tested against the same task set, comparing completion quality, tool-call overhead, execution time, and safety violations.
Evaluation cases should be separate from the examples used to generate candidate procedures. Otherwise, a candidate may merely reproduce familiar answers. An optimization may benefit only certain tasks, so retain the previous version and support rollback.
If model parameter training is involved, data licensing, privacy de-identification, training resources, and model regression testing must be handled separately. Training should not be treated as an incidental part of updating the skill library.
6. Configure Coding, Research, and Design Roles
6.1 Coding Agents: Control Write and Execution Permissions
A coding role can access a designated code workspace, read requirements, and run restricted tests. Its default sequence should be analysis, modification, and verification.
Authorize file reading, file modification, program execution, and network access separately. Operations such as deleting directories, changing critical configuration, or publishing deliverables should require human confirmation.
Long-term memory should retain project conventions and confirmed development standards, not access credentials.
6.2 Research Agents: Preserve Evidence and Source Boundaries
A research role should distinguish source facts, quoted material, and its own inferences. Conclusions should identify their evidentiary basis, and information that cannot be verified should be clearly labeled.
Retrieved pages and documents are external data. Instructions embedded in them must not automatically become system commands. A document asking the agent to “upload local files” must not grant it access to private directories.
6.3 Design Agents: Manage Requirements and Deliverable Versions
A design role can retain confirmed visual constraints, delivery specifications, and feedback, but it must distinguish temporary exploration from final decisions.
Each revision should record the input requirements, changes made, and delivery status. This prevents rejected proposals from becoming long-term preferences. Reference materials also require attention to source, licensing scope, and permitted use.
6.4 Isolation Must Be Enforced in Storage and Permissions
Giving three roles different names or prompts creates behavioral distinctions, not security isolation. At a minimum, configure separate:
- Identities and access credentials.
- Working directories and memory namespaces.
- Skill libraries and permitted tools.
- Message sessions and task queues.
- Runtime budgets and log access permissions.
When roles need to share knowledge, establish a controlled shared area with explicit write, review, and read permissions. Higher-security environments should also use separate execution environments and network access policies.
7. Continuous Operation Requires Engineering Support
Running around the clock means more than keeping a process open. The system must handle process failures, network instability, task backlogs, duplicate messages, and unavailable external dependencies.
At a minimum, provide the following mechanisms:
Task persistence. After a restart, the system should identify unfinished tasks. Whether execution resumes must depend on task state and operation records, not blind retries.
Side-effect deduplication. Before sending a message, creating a resource, or submitting a result, check whether the same operation has already completed. Steps that cannot be reliably deduplicated should receive additional human review.
Failure classification. Network timeouts may justify limited retries. Insufficient permissions generally do not. Missing input should trigger a request for clarification.
Observability. Record request identifiers, roles, tool calls, approval outcomes, error types, and resource consumption. Logs should be sanitized so they do not become a second repository of sensitive information.
Health checks and alerts. Monitor not only whether the process is alive, but also task wait times, consecutive failures, and tool availability.
8. Implement in Stages and Finish with Acceptance Criteria
Build in this order: a minimal single-role execution loop, memory governance, skill publication, multi-role isolation, and continuous operation. Avoid introducing every capability at once.
The first stage should cover request intake, tool authorization, result delivery, and audit records. The second adds long-term memory that can be queried and deleted. The third establishes candidate skill review and rollback. The fourth verifies resource boundaries between roles. Only then should scheduled tasks, automatic recovery, and operational alerts be added.
Before deployment, verify at least the following:
- Task state can be recovered after a restart without repeating critical operations.
- Withdrawn user preferences stop influencing subsequent tasks.
- Unreviewed high-risk skills cannot be invoked.
- Malicious instructions in external documents cannot expand permissions.
- Each role can access only authorized data.
- Failed tasks provide an explanation and retain the necessary evidence.
- Regressions caused by new skills or configuration changes can be rolled back quickly.
The goal of a learning agent is not to remember as much as possible. It is to ensure that every retained lesson has a source, a defined scope, and supporting validation.
A unified execution core provides consistency across interfaces. Layered memory preserves context continuity. Skill governance enables controlled reuse of experience. Offline evaluation establishes whether changes actually help. Permission isolation and operational monitoring support sustained execution. Together, these components allow an agent to move beyond an occasionally effective demonstration and become a maintainable working system.
