Building Production-Grade AI Agents: A Five-Layer Configuration Path

    When teams first integrate general-purpose conversational models into AI agents, they often expect them to remember context, retrieve information, generate multimodal content, and control costs. However, post-launch realities include memory loss across sessions, unverifiable retrieval results, repeated tool calls, and escalating latency and costs. The gap usually lies not in model parameters, but in whether identity, memory, perception, expression, cost, and navigation are structured into a verifiable chain. This article details a five-layer engineering framework to configure production-ready AI agents, covering system design principles, actionable configuration steps, and acceptance criteria for each layer.

    When teams first integrate a general-purpose conversational model into an AI agent, they expect it to “remember me, search for information, generate images and text, and keep costs under control.” After launch, however, they discover that it loses memory when sessions change, retrieval results cannot be verified, repeated tool calls occur when tools scale, and both bills and latency rise simultaneously. The gap usually lies not in the model parameters themselves, but in whether identity, memory, perception, expression, cost, and navigation are structured into a verifiable chain. Below is an engineering perspective on what problems these five layers solve, how to configure them, and how to verify they are done right.

    Clarifying the Goal: Configuring a Working System, Not a Longer Prompt

    An AI agent can be understood as a system that uses role constraints, state storage, tool permissions, output specifications, and observability outside the large language model (LLM) to turn individual conversations into repeatable task execution. Prompts remain important, but they are only part of the identity layer. If you merely pile on adjectives like “you are an expert,” the model will still lose facts across sessions, fabricate sources during retrieval, and lack input/output contracts for image or voice generation.

    Before starting configuration, it is recommended to write down three acceptance criteria:

    • Continuity: When the same user or project resumes the next day, the agent should recall confirmed goals, constraints, and pending items, rather than relying on the user to repeat them verbally.
    • Traceability: External information must include its source, time, and scope of application. The model must not rewrite retrieval summaries as firsthand facts.
    • Controllable Cost: Each task has limits on steps, context length, and tool quotas. Exceeding these limits should trigger degradation rather than infinite retries.

    Without these three criteria, subsequent features like “role libraries,” “web crawling,” and “multimodality” easily turn into feature bloat.

    Layer 1: Identity and Memory — Switchable Roles and Persistent Facts

    Identity answers the question: “What professional standard am I working to right now?” Memory answers: “What information remains valid across sessions?” These two should not be written into the same unmaintainable, long prompt.

    Identity files should be short and versionable, containing at least: scope of responsibility, input/output formats, prohibited actions, and definition of done. For example, an analysis role must provide hypotheses and data gaps; an execution role must list steps before calling tools. Roles can be split by function, such as R&D assistance, proposal writing, test design, or operations review. However, switching roles should be explicitly declared to avoid persona drift within a single session.

    Schematic structure (field names are illustrative, not specific product APIs):

    1. role: Technical Writing Assistant
    2. scope: Only based on provided materials and authorized data sources
    3. deliverable: Outline, body, fact-check list
    4. never: Fabricate citations, leak keys, bypass access control
    5. done_when: Structure is complete and every key conclusion is traceable to a source

    Memory must be layered, rather than “permanently stuffing the entire chat history into the context”:

    • Session State: Current goals, confirmed decisions, to-do items. Short lifecycle; can be archived when the task ends.
    • User State: Preferences, glossaries, prohibited styles. Users must be able to view and delete these.
    • Project State: Repository conventions, API contracts, environment differences. These should sync with project documentation, not just live in the conversation.
    • Organization State: Compliance red lines, external PR narratives. Changes require review and must not be rewritten by the model autonomously.

    Before writing to memory, there should be a “confirmation gate”: explicit user consent, or the system determines it is a stable fact (e.g., a merged requirement number). Do not store small talk, guesses, or ephemeral emotions. When recalling, truncate by relevance, and distinguish “preferences in memory” from “new instructions for this session” in the response. In case of conflict, the explicit new instruction takes precedence, while noting that old memory may be outdated.

    A common failure is treating the role repository as a universal switch. No matter how many templates exist, without a definition of done and memory layering, switching roles merely changes the tone. For maintenance, each role should be an independent, reviewable, and rollbackable document. Use a few sample conversations for regression testing, rather than casually modifying tens of thousands of words of prompts in production conversations.

    Layer 2: Perception Capabilities — Turning External Info into Citable Evidence

    “Being able to access the internet” does not equal “reliable evidence.” Production environments should prioritize authorized retrieval APIs, enterprise internal knowledge bases, user-uploaded materials, and publicly distributable documents. Access control, quotas, and auditing should be placed in the tool layer, rather than relying on the model’s self-awareness.

    The recommended perception pipeline is: Query Rewriting → Authorized Retrieval → Snippet Extraction → Contradiction Detection → Cited Response. Query rewriting translates colloquial language into searchable keywords and time ranges. Snippet extraction sends only relevant paragraphs into the context, avoiding injecting entire pages. Contradiction detection requires listing discrepancies when multiple sources disagree, rather than picking the one that sounds best.

    It is not recommended to treat “bypassing access restrictions, spoofing clients, or bulk scraping unauthorized pages” as capability goals. Such practices are unstable and easily violate website terms, copyright, and data compliance. If public pages cannot be stably accessed, the correct degradation is: explain the missing data, ask the user to provide the original text, or switch to a formal data API. For dynamic pages, prioritize official or purchased data services. Self-built crawlers should only process sites the organization has the right to collect, adhering to rate limits and robots.txt conventions.

    Batch tasks require separate design: separate lists from details, allow retries with a cap on failures, and store raw snapshots separately from extracted results. Object storage is suitable for raw snapshots, search indexes for chunked text, and logging services for query terms, hit documents, and timestamps. This allows you to answer “what did the model actually see at that time” later, rather than being left with an unverifiable conclusion.

    Layer 3: Expression Capabilities — Establishing Contracts for Voice and Image

    Multimodality is not just casually appending “draw a picture” to the end of a text output. Speech recognition (ASR), text-to-speech (TTS), and image generation each have their own input quality, latency, copyright, and failure modes.

    Voice input must handle noise, proper nouns, and speaker switching. The recognition result should first provide user-verifiable text before entering subsequent reasoning, preventing transcription errors from being written into long-term memory. Voice output should limit length and sensitive content, provide a text fallback, and avoid relying solely on fleeting audio for critical numbers, account details, or operation confirmations.

    Image generation requires visual specifications first: usage, size, style constraints, required and prohibited elements, and whether text is allowed. Models are not good at precise long-text layout; poster titles and data charts are better suited for templates or visualization components, while generated images serve mainly as illustrations. For people, trademarks, and copyrighted characters, generating recognizable imitations should be disabled by default. Outputs should retain prompt versions and generation parameter summaries for reproducibility, but must not include API keys in the prompts.

    Acceptance criteria can be highly specific: the same role delivers consistent structures across three consecutive tasks; the voice pipeline falls back to typing upon recognition failure; and if an image violates constraints, the system points out which specification was unmet, rather than blindly retrying.

    Layer 4: Cost and Efficiency — Treating Tokens and Tool Steps as a Budget

    High costs often occur because terminal outputs, full web pages, conversation history, and tool return packets are all sent back to the model verbatim. The governance principle is “send less, send in batches, make it stoppable.”

    • Context Budget: Allocate limits across system constraints, roles, memory summaries, retrieval snippets, and current user input. Use summary pointers for memory instead of repeatedly pasting full history.
    • Tool Budget: Maximum calls per task, per-tool timeouts, and deduplication of repeated calls. If the same command fails twice, ask the user for an error summary instead of replaying a massive log verbatim.
    • Output Budget: Generate outlines or diffs first, then expand as needed. Keep only relevant lines of code and logs.
    • Caching: Stable role descriptions and project specs can use prompt caching or server-side caching; do not cache volatile facts for too long.
    • Observability: Track input/output lengths, steps, failure rates, and cost per unit task by user, role, and tool. Without this dashboard, you cannot tell if optimizations are effective.

    Do not promise fixed “percentage reductions.” Savings depend on how verbose the original logs were and how coarse the retrieval was. A reasonable goal is: without degrading answer quality, compress invalid context and redundant tool calls, and provide clear degradation (answering only known parts, escalating to a human, or switching to asynchronous) for over-budget tasks.

    Terminal-based tools must especially prevent “sending the entire screen buffer to the model.” Tools should truncate and desensitize (removing keys, tokens, PII) on their side before returning a summary. This simultaneously reduces costs and leakage risks.

    Layer 5: Capability Navigation — Discoverable but Non-Exceedable Resources and Permissions

    As roles, tools, and knowledge bases multiply, users need a directory of “what can be done and what cannot,” rather than having all tools enabled by default. The navigation layer includes: a capability catalog, required permissions, example tasks, and who to contact on failure. The directory itself should also be versioned.

    Permissions follow the principle of least privilege: read-only retrieval and write operations are separated; external sending, payment, and deletion actions require secondary confirmation. New roles should enter a sandbox first, run regression tests with fixed prompts, and then move to production. On standard cloud platforms, you can typically use object storage to save snapshots and role documents, use search or vector capabilities for knowledge recall, and use monitoring and alerting to observe call volumes and failure rates. Specific deployment depends on actual accounts and compliance reviews, and unverified custom integrations should not be assumed.

    An Actionable Configuration Sequence

    You don’t need to configure everything at once. Proceed according to dependencies, with exit criteria for each step:

    1. Write a one-page identity description and definition of done. Run three real tasks to see if the delivery structure is stable.
    2. Launch conversation summaries and user-deletable preference memory. Disable automatic writing of unconfirmed facts.
    3. Connect an authorized knowledge source and mandate cited responses. If it can’t answer, explicitly state the unknown.
    4. Choose one scenario to build an end-to-end contract for voice or image, keeping everything else text-based.
    5. Add step limits, length limits, and desensitization truncation. Enable per-task usage statistics.
    6. Compile the capability catalog and permission matrix. Turn off default full-tool access.
    7. Conduct a one-week regression: spot-check whether memory is polluted, citations open correctly, over-limit tasks degrade, and costs are explainable.

    Boundaries to Maintain Post-Launch

    An AI agent does not gain new factual authority just because it has more configurations. It excels at organizing information, calling tools, and maintaining formats within constraints. Configurers must continuously handle expired memory, retrieval bias, multimodal misrecognition, and prompt injection (where users or web pages ask the model to ignore rules or leak keys). Text returned by tools must always be treated as untrusted data that cannot override system constraints.

    By designing and accepting these five layers separately, the difference between a raw configuration and a deliverable configuration becomes explainable: it’s not about swapping in a “smarter species,” but rather having identity boundaries, memory lifecycles, authorized perception, expression specs, cost budgets, and a capability catalog. Iterating in this order transforms an agent from a chat companion into an auditable, productive component of the team.