Building LLM Agents from Scratch: Architecture Design and Engineering Practices
This article explains how to transform large language models into production-ready AI agents. It covers when an agent is actually needed, how to define task contracts, a six-layer reference architecture, task planning, tool calling, model routing, memory management, multi-agent collaboration, industry use cases, evaluation and safety, and a phased path from prototype to system-level agents. Readers will learn practical engineering principles for making agent goals checkable, actions constrained, results verifiable, and failures recoverable.
1. From Dialogue Model to Agent: What Actually Changes
Large language models can understand natural language, generate text, and support reasoning. Used in isolation, however, a model typically maps a single input to a single output. An agent adds state, tools, and feedback mechanisms around the model, enabling a system to perform multi-step tasks toward a goal.
A typical agent workflow is: receive a goal, understand constraints, choose the next action, invoke a tool, read the execution result, and decide whether to continue or stop. For example, when a user asks to “check the order status and process a refund that meets the rules,” the system must not only understand the question but also verify identity, query the order, evaluate policy compliance, confirm permissions, and check the result after execution.
Therefore, an agent should not be understood simply as “a chatbot with added prompts.” It is closer to a task-processing system in which a model participates in decision-making while engineering systems constrain execution.
To decide whether you need an agent, answer three questions:
- Does the task path vary with input and execution results?
- Does the system need to access external data or perform real operations?
- Does the system need to adjust subsequent steps based on feedback?
If the process is fixed and the rules are clear, a traditional workflow is often easier to test and control. Agents add value only when tasks involve significant uncertainty and require dynamic step or tool selection. Real-world projects usually adopt a hybrid approach: deterministic rules govern critical business flows, while the model handles intent understanding, information extraction, and limited-scope decisions.
2. Define the Task Contract Before Choosing a Model
Many prototypes demo well but fail to go live reliably, because success criteria were never defined. Before development, translate vague requirements into a checkable task contract.
A task contract should include at least:
- Goal: What outcome the system must ultimately produce.
- Inputs: User requests, business data, and necessary context.
- Allowed actions: Which resources may be queried, modified, or submitted.
- Prohibited actions: Which behaviors must be rejected or escalated to humans.
- Completion criteria: What evidence confirms the task is complete.
- Resource budget: Allowed execution time, model calls, and tool invocations.
- Failure handling: How the task ends on timeout, insufficient permissions, or uncertain results.
For example, “process a refund” is not a sufficiently precise goal. A better definition is: “Verify that the applicant matches the order owner, determine eligibility according to valid refund rules; if eligible, generate a pending approval request; submit only after the required authorization is obtained; and report the result based on the business system’s status.”
This definition separates the model’s language capability from the system’s operational permissions, avoiding the mistake of treating “the model thinks it succeeded” as “the business actually succeeded.”
3. Adopt a Six-Layer Reference Architecture
The six-layer architecture is a convenient engineering decomposition, not the only standard. Its value lies in clarifying responsibilities and preventing all logic from piling up in prompts.
3.1 Interaction and Access Layer
This layer receives user input, verifies user identity, maintains sessions, and displays task status. Inputs may be text, documents, or other business materials, which should be normalized into a unified task description after entering the system.
The access layer should also handle request cancellation, duplicate submission, and user confirmation. For time-consuming tasks, the interface should distinguish among “received,” “in progress,” “awaiting authorization,” and “completed,” rather than showing a single waiting state indefinitely.
3.2 Orchestration and Control Layer
The orchestration layer maintains task state and decides when to call the model, execute tools, wait for a human, or end the process. It is the control core of the running agent.
Production-grade orchestration typically requires explicit states, for example:
Pending → Information Completion → Plan Generation → Action Execution → Result Verification → Complete
There must also be branches for failure, cancellation, and human takeover. For longer tasks, execution checkpoints should be saved so the process can resume after interruption instead of re-executing every step.
3.3 Model and Decision Layer
The model handles intent recognition, task decomposition, candidate action selection, and result summarization, but it should never be given unrestricted execution capability.
In engineering terms, treat model output as “a decision suggestion pending validation.” The system must check the output structure, verify that actions are legal and parameters satisfy constraints, and only then execute. For critical business judgments, corroborate with explicit rules or verifiable data.
3.4 Tools and Execution Layer
The tool layer encapsulates capabilities such as querying databases, retrieving documents, and submitting business requests as controlled operations. Every tool should document its purpose, input requirements, output structure, permission scope, and possible side effects.
Query operations and mutation operations should be managed separately. Mutating tools require stricter authorization, idempotency control, and auditing. A model proposing “delete data” does not mean the system should immediately execute it; the execution layer must still verify the caller’s identity, the target resource, and the scope of the operation.
3.5 Knowledge and Memory Layer
This layer stores current task state, historical summaries, business knowledge, and reusable experience. It must help the model obtain necessary information while controlling the timeliness, provenance, and access permissions of that information.
Knowledge material should not be pasted into context as plain text alone; it must retain source, version, and update time. This enables the system to explain its reasoning and prevents it from continuing to cite outdated rules after a policy change.
3.6 Governance and Observability Layer
Governance and observability span all layers: identity authentication, data protection, audit logging, quality evaluation, cost accounting, and anomaly alerting.
Note that “layer six” does not mean security is handled last. Permission checks must occur every time a resource is actually accessed, and sensitive information controls must cover inputs, storage, tool returns, and final outputs.
4. Task Planning: Keep Dynamic Capability While Limiting Freedom
Planning turns a goal into steps that can be executed and verified. Common approaches include generating a complete plan at once, and planning incrementally based on feedback after each step.
One-shot planning suits tasks with relatively stable processes and clear dependencies; its advantage is that risks can be checked in advance. Incremental planning suits exploratory tasks but is more prone to repeated calls, goal drift, and over-execution.
In practice, combine the two: generate a high-level plan first, then decide concrete actions within each stage based on feedback. Each subtask should specify its inputs, expected outputs, dependencies, and completion criteria.
For example, generating an analysis report can be decomposed into:
- Clarify the analysis scope and time range;
- Obtain authorized data;
- Check missing values, outliers, and statistical definitions;
- Perform calculations and record intermediate results;
- Generate conclusions, annotating evidence and uncertainty;
- Verify that conclusions are consistent with the data.
The system must also set explicit stop conditions. Reaching the goal, exhausting the resource budget, repeated failures, insufficient permissions, or the need for human confirmation should all trigger termination or takeover — not infinite retries by the model.
5. Tool Calls: Make Execution Results Reliable Facts
Tool calling is where an agent connects to real business systems, and it is also where risk concentrates. Design tools with single responsibilities, explicit parameters, and verifiable results.
Avoid providing a generic entry point that can execute arbitrary operations; instead, offer limited business capabilities. For example, splitting “query order,” “calculate refundable amount,” and “submit refund request” into separate operations facilitates permission isolation and fault localization.
Here is an illustrative control flow, not tied to any specific product interface:
Task = CreateTask(user request)Budget = InitializeBudget()While task is not finished and budget remains:Context = Read necessary state and authorization infoSuggestion = Model generates next action(Context)If suggestion structure is invalid:Log the issue and perform a limited number of correctionsContinueIf action exceeds permitted scope:Reject execution and end the taskIf action requires additional authorization:Save checkpointTransition to awaiting-confirmation stateEnd current executionResult = Controlled execution of action(Suggestion)Save action, result, and state changesConsume execution budgetIf result satisfies completion criteria:End the taskElse if result cannot be safely recovered:Escalate to human handling
For execution failures, distinguish transient faults from business rejections. Network timeouts can be retried within controlled limits, but insufficient balance, insufficient permissions, or rule violations should not be resolved by repeatedly calling.
A critical point: a request timeout does not mean the operation failed. After a submission times out, first query the business status or rely on idempotency identifiers to confirm the outcome, avoiding duplicate refunds, payments, or other business records.
6. Model Routing: Allocate Capability by Task Risk
Model routing is not simply selecting the “strongest” model for every request; it allocates models based on task complexity, input length, latency budget, cost, and risk.
Simple classification, field extraction, and fixed-format rewriting can use cheaper processing paths; complex planning, long-document analysis, or high-risk conclusion generation require stronger capability and validation.
Routing design should cover three types of decisions:
- Initial selection: choose a processing path based on task characteristics;
- Dynamic escalation: switch to a more suitable path when validation fails or task complexity increases;
- Safe degradation: fall back to rule-based flows, limited answers, or human service when the model is unavailable or unreliable.
Do not rely solely on a model’s self-reported “confidence” to decide whether to execute a high-risk action. More reliable signals include field completeness, evidence coverage, rule validation results, and historical evaluation performance. Routing strategies should also be validated with fixed test sets to ensure that cost savings do not significantly degrade task completion quality.
7. Memory Management: Store What Matters, Don’t Accumulate Endless History
Agent memory falls into three categories:
Working memory holds the current task’s goals, constraints, completed steps, and open issues; its purpose is to support task continuity.
Long-term memory stores authorized user preferences or reusable experience, with explicit retention periods, update methods, and deletion mechanisms.
Knowledge material holds business rules, documents, and factual content, with attention to versioning, provenance, and retrieval permissions.
Permanently placing the entire conversation history into context both increases cost and introduces stale information and privacy risks. A better approach is to store key state in a structured way and generate traceable summaries of the history.
Summaries can lose information, so important facts should retain their original evidence or reference locations. Inferences made by the model must not be written into long-term facts without verification. Memory must also handle conflicts: a user’s currently expressed preference should take precedence over historical records, and newly effective business rules should replace outdated versions.
8. Multi-Agent Systems: Prove the Benefit Before Adding Collaborative Complexity
Multi-agent setups suit tasks that can be clearly divided, executed in parallel, or cross-checked. For example, one role retrieves material, another analyzes it, and a third checks whether conclusions are supported by evidence.
However, adding roles does not automatically improve quality. If multiple roles share the same erroneous material, repeated discussion may only reinforce the same mistake. Multi-agent systems also increase call costs, communication overhead, and state-management complexity.
When designing a collaborative system, be explicit about:
- The input and output contracts for each role;
- Which role is responsible for final aggregation;
- What rules resolve conflicts;
- Whether roles may directly invoke business tools;
- How a single role’s failure is isolated;
- How the overall execution budget is allocated.
For simple tasks, a single agent with deterministic tools is usually more appropriate. Multi-agent architectures are worth adopting only when evaluation demonstrates that specialization, parallelization, or independent verification brings real benefits.
9. From Reproducible Cases to Production Deployment
Customer Service and Business Operations
Customer-service agents can start with policy retrieval and response suggestions, then gradually add controlled query capabilities. Before launch, build test cases covering identity mismatches, policy conflicts, missing information, and duplicate user requests.
Evaluation must check not only whether answers are fluent, but also whether the supporting evidence is correct, sensitive information is protected, and processing outcomes are genuine. For operations involving refunds or account changes, risk should be controlled through business permissions and confirmation mechanisms.
Creative Generation and Content Production
Creative tasks fit a “requirement clarification — draft generation — constraint checking — human selection” workflow. The system should validate topic, audience, length, and prohibited content, not just pursue novelty of expression.
When retrieval material is used, distinguish factual citations from creative elaboration. Unverified numbers, cases, or effect descriptions must not be presented as facts in the final copy.
Programming Automation
Programming agents should read code in an isolated environment, propose changes, run tests, and submit reviewable changes. Their completion criterion should be passing tests and constraint checks — not the model claiming “the problem is fixed.”
Beyond regular tests, pay attention to dependency changes, sensitive configurations, file access scope, and security vulnerabilities. When executing generated code, restrict network, file, and credential access, and retain human review for important changes.
Financial Decisions and Healthcare
These domains demand higher accuracy, clearer accountability boundaries, and stricter compliance. It is advisable to start with low-autonomy tasks such as information organization, risk alerts, and assisted analysis, rather than treating generated content as equivalent to professional conclusions.
Financial transactions involve real asset changes and require independent risk-control rules, authorization approvals, and abnormal-stop mechanisms. Healthcare scenarios must protect sensitive information, preserve evidence, and escalate to professionals when necessary. The system must be explicit about its capability boundaries: automated output cannot replace judgments that qualified professionals are required to make.
10. Build Evaluation, Observability, and Security Together
Agent evaluation should cover both outcomes and process. Outcome metrics include task completion rate, factual accuracy, and goal attainment; process metrics include tool-call legality, repeated operations, execution time, resource consumption, and human-takeover ratio.
Test sets should include normal samples, boundary samples, and adversarial samples. For example, retrieved documents containing text instructing the system to ignore its rules are an indirect prompt-injection risk that must be guarded against. External material should be treated as data to be processed, not as high-priority instructions.
Tool outputs are equally untrusted. The system should limit their influence: external text must not change permissions, solicit credentials, or induce sending data without authorization. Security cannot rely on a single sentence like “follow the rules”; it requires least-privilege execution, resource isolation, and output review.
Observability records should be able to correlate model calls, tool calls, and state changes within the same task, while masking sensitive fields. Records should focus on auditable inputs and outputs, decision summaries, and execution evidence, without needing to store the model’s internal reasoning process.
After launch, periodically review failure cases, policy changes, and abnormal costs. Good offline test performance does not mean the system can run indefinitely without maintenance.
11. A Phased Path from Prototype to System-Level Agent
Proceed in the following order:
Phase 1: Choose a limited-scope, low-risk task, define completion criteria, and establish a rule-based flow as the baseline.
Phase 2: Introduce the model for understanding and structured output, but keep execution manual; verify whether it genuinely reduces workload.
Phase 3: Open read-only tools; evaluate retrieval quality, permission isolation, and exception recovery.
Phase 4: Open limited write operations, once necessary authorization, idempotency control, and auditing are in place.
Phase 5: Add dynamic planning, long-term memory, or multi-agent collaboration based on evaluation results — not all capabilities at once.
The essence of a system-level agent is maintaining consistent identity, permissions, state, and accountability across multiple business stages. It must coordinate workflows, messaging, storage, and human approvals, and be able to give clear explanations when a task is paused, fails, or recovers.
The future agent ecosystem may evolve toward more standardized tool descriptions, more reliable capability discovery, and finer-grained authorization mechanisms. But regardless of how underlying models evolve, the engineering principles remain unchanged: make goals checkable, make actions constrained, make results verifiable, and make failures recoverable. Only on this foundation can an LLM agent move from a demo prototype to a business system that runs sustainably.
