Building LLM Agents from Scratch: Design Principles and Engineering Practice

    This article presents an engineering framework for building LLM agents from scratch without relying on a specific orchestration product. It covers the capabilities agents add, design principles for usable and extensible systems, a six-layer architecture and call chain, planning/tool/memory design, security and observability, common application patterns, and the path from demos to production. Readers will learn how to structure agents around boundaries, verification, and feedback so they remain auditable and cost-effective as tasks grow more complex.

    Large language models excel at generation and reasoning, but a single question-answer interaction rarely completes real tasks that span multiple steps and systems reliably. The problem agents solve is connecting intent understanding, goal decomposition, capability invocation, result verification, and continuous correction into a closed loop. This article rebuilds a knowledge framework from principles to implementation from an engineering perspective. It does not depend on a specific orchestration product; instead, it focuses on reusable design principles.

    What Capability Do Agents Add?

    Rule-based systems hard-code conditions. They respond quickly and have clear boundaries, but they are fragile when faced with open-ended expressions. Planning-based systems emphasize beliefs, desires, and intentions: first form a judgment about the world, then choose the state to achieve, and finally map that to actions. With LLMs, a single agent can compress these three steps into one cognitive loop: absorb context in natural language, generate steps through planning, change external state through tools, and use observations to decide whether to continue.

    Whether to train an agent specifically depends on whether the task is stable, whether data can be accumulated, and whether the cost of errors is acceptable. In most enterprise scenarios, teams should first solidify prompts, tool contracts, memory, and evaluation. Only when a general model repeatedly fails in a specific domain and sufficient labels and feedback exist should they consider fine-tuning or reinforcement-learning-style policy optimization. Training addresses in-distribution stability; architecture addresses whether a task can be decomposed, audited, and replaced.

    Multi-agent systems are not “calling a model several times.” They separate roles, permissions, and communication protocols: one agent clarifies requirements, another retrieves and computes, and another reviews. The value of collaboration lies in specialization and mutual constraint; the cost is latency, state consistency, and responsibility boundaries.

    Design Principles: Usable First, Smart Second

    User-friendliness means a unified entry point, explainable process, and recoverable failure. Users should not care how many internal modules exist. They should see clear progress, necessary confirmations, and revocable results.

    System intelligence should be measured not by fluent answers but by whether the system correctly understands constraints and completes the task. When intent is ambiguous, the agent should ask follow-up questions rather than guess and directly execute high-risk actions.

    Extensibility comes from module boundaries: input adaptation, intent routing, planning, execution, reasoning verification, and feedback learning should be decoupled. Replacing one layer should not require rebuilding the entire stack.

    Cost-effectiveness requires choosing models and invocation counts based on task difficulty. Simple classification does not need a long chain. Only multi-step, multi-tool, high-uncertainty tasks should enable full planning and review. Cost, latency, and accuracy must be evaluated together.

    Six-Layer Architecture and Call Chain

    The system can be viewed as six layers rather than one giant prompt.

    The input layer uniformly receives text, voice transcripts, image descriptions, or structured forms, and maintains session state: user identity, permissions, current task, and unfilled slots. Multimodal inputs are first normalized into a semantic representation consumable by the model before entering subsequent layers, avoiding each downstream module parsing formats on its own.

    The intent layer determines “what to do.” In engineering, there are three common paths: prompt-based classification for cold start; lightweight classifiers for high-frequency intents with stable labels; and function or tool selection for scenarios with clear action boundaries. These can be cascaded: first coarse classification, then selection within a candidate tool set. Routing should also support an agent registry: each agent declares capabilities, input/output contracts, risk level, and applicable conditions, and the router dynamically matches them by intent and policy instead of hard-coding branches.

    The planning layer decomposes goals into executable steps, specifying dependencies, required tools, expected observations, and stopping conditions. Plans should not be generated once and executed blindly. A more robust approach is short planning, step-by-step execution, and replanning based on observations.

    The execution layer does one thing: invoke tools or downstream services according to contracts. Tool descriptions should include purpose, parameters, preconditions, and failure semantics. The executor handles authentication, timeout, retry, and idempotency. It does not improvise.

    The reasoning and verification layer checks intermediate results against the goal: whether the format is valid, whether values are within range, whether citations come from retrieval results, and whether policies are violated. If verification fails, the system returns to planning or requests human confirmation.

    The feedback layer records trajectories: input, plan, tool calls, observations, final answer, and user corrections. These trajectories are used for evaluation, regression, and subsequent optimization, not treated directly as unauditable implicit memory.

    A typical call chain is: ingest and complete context → identify intent and select an agent → generate a limited-step plan → execute tools according to permissions → update state with observations → verify or replan → output and write feedback. Any layer can terminate early due to risk policy.

    Planning, Tools, and Memory

    Task planning should explicitly state success criteria. For example, in a customer service scenario, success criteria can be “identity verified, order located, and an executable next step provided,” not “friendly tone.” Step granularity should map to one tool call or one explicit reasoning step. Too coarse and retries are impossible; too fine and invocation costs increase.

    The key to tool invocation is contracts, not prompt tricks. Parameters should be described with structured constraints. Only expose the tools needed for the current step to the model to reduce the choice space. For write operations, add confirmation or secondary validation by default. An illustrative loop is shown below:

    1. state = load_context(session)
    2. intent = route(state)
    3. plan = propose_plan(intent, tools=allowed(intent), budget=limits)
    4. while not done(plan, state) and steps < max_steps:
    5. action = next_action(plan, state)
    6. if risk(action) == high and not confirmed:
    7. return ask_user(action)
    8. obs = execute(action) # auth, timeout, idempotency
    9. state = update(state, obs)
    10. plan = revise(plan, state)
    11. return answer_with_evidence(state)

    Memory is clearer in three layers. Working memory is the slots and intermediate results of the current session. It has a short lifetime and must be clearable. Episodic memory stores retrievable summaries of historical interactions. Before writing, it must be de-identified and annotated with source and time. Long-term knowledge lives in retrieval stores or business systems. The model only consumes retrieved snippets and does not “remember” business facts in its weights as authority. Forgetting, correction, and permission filtering are as important as writing: content a user is not allowed to see should not appear in that user’s context.

    Model routing distributes traffic by difficulty, modality, latency, and cost. Classification and extraction use smaller models. Multi-step planning and conflict verification use more capable models. Failures escalate rather than defaulting to the most expensive path. Routing policies themselves should be configurable and replayable, making it easy to compare the impact of different routes on accuracy and cost.

    Security, Compliance, and Observability

    Agent risk concentrates in unauthorized tool calls, prompt injection, and hallucinations being executed as facts. Protection should be built into the architecture: register tools with least privilege; treat external content as untrusted data that cannot override system policy; require human confirmation or dual-control rules for high-risk actions such as funds, permission changes, and bulk outbound messages; and require outputs to provide evidence for key facts or explicitly state “unknown.”

    Logs must be able to reconstruct why a task called a certain tool, what evidence was used, and who approved it. Metrics should include at least task completion rate, human handoff rate, tool failure rate, average number of steps, and cost per task. Without these, it is impossible to tell whether the system is getting smarter or just more expensive.

    For compliance, collect personal information minimally, store memory and logs separately, and set retention periods. In scenarios such as healthcare and financial decisions, position the system as information organization and process assistance. Key conclusions should be finally confirmed by qualified personnel or existing business rules, and generated results should not be treated directly as diagnostic or trading instructions.

    Applying the Same Skeleton in Scenarios

    Customer service: route intents to subflows such as inquiry, change, and complaint; put identity verification first; use retrieval as the source of truth for knowledge; and when the loop cannot be closed, hand off smoothly to a human with collected slots.

    Creativity and content: planning focuses on outlines, material constraints, and style consistency; tools provide retrieval and templates; verification checks facts and brand guidelines rather than only literary quality.

    Programming automation: split repository search, static checks, and test execution into tools. After an agent proposes a patch, it must pass tests and human review and is prohibited from being pushed directly to protected branches.

    Financial decision support: use tools to read authorized market data and position summaries, and output scenario analysis and risk warnings. If write operations such as order placement or rebalancing exist, they must go through independent risk control and confirmation, not implicit execution in the conversation.

    Healthcare: handle appointments, queries about medication reminder standards, and structured organization of test reports. When diagnosis and medication advice are involved, clearly define boundaries and guide users to professional processes.

    These scenarios share the same six-layer skeleton. Differences lie in tool sets, risk levels, and success criteria, not in a separate “mysterious architecture.”

    System-Level Agents and Future Evolution

    When agents move from demos to production, design focus shifts from single prompts to the control plane: registration, versioning, canary release, quotas, circuit breaking, and evaluation sets for agents and tools. Multi-agent systems should communicate through explicit message contracts and avoid infinitely forwarding long contexts to each other. An ecosystem trend is componentized capabilities: planning strategies, memory backends, verifiers, and executors can all be replaced independently; the model is just one routable reasoning engine among them.

    A recommended implementation order is: first choose a task with a short closed loop, few tools, and rollbackable failures; fix an evaluation set; connect permissions and logging; then gradually add memory, multiple models, and multiple roles. Agent reliability comes from boundaries, verification, and feedback, not from stacking more prompts into a single call. Building according to these principles allows the system to evolve with business growth instead of losing control at the first complex task.