AI Agent Implementation: Memory, Cost Control, and Skills

    This article explains how to build production-ready AI agents around three engineering concerns: persistent memory, deterministic execution, and controllable per-task cost. It covers a three-layer memory architecture (facts, events, summaries) with a minimal SQL schema, a tiered execution strategy that routes deterministic work to scripts and reserves model calls for semantic judgment, model routing with fallback and budget limits, always-on edge deployment with process supervision and least-privilege permissions, edge-cloud collaboration, a local Markdown knowledge base as a control panel, and a skill-based approach for packaging recurring friction points. A final implementation checklist covers observability thresholds for cost, success rate, and latency. The guidance is vendor-neutral and relies on common industry components and practices.

    1. Where the Problem Starts: An Agent’s Real Value Is Not Conversation

    When teams evaluate AI agents, the first instinct is often to check whether the language output is fluent and whether the context window is long enough. What actually determines whether an agent can reach production is three other things: whether state can be persisted, whether the execution path is deterministic, and whether the cost per task is controllable.

    An agent that only “talks” loses its memory the moment a session ends. Users have to restate the background repeatedly and paste keys and parameters again and again. If the process restarts, a long-running flow breaks and the task starts over from the beginning. Systems like this look good in a demo, but in high-frequency daily use they quickly expose three typical problems: broken flows caused by frequent restarts, repeated instructions caused by missing memory, and runaway token spend caused by too many model calls.

    This article therefore abstracts the topic away from any specific product experience into a general engineering question: how to build an AI agent with persistent memory, deterministic execution, and controllable cost. The approach below does not depend on any particular vendor product and is based on common industry components and widely used practices.

    2. Memory Systems: From In-Session Context to Searchable Persistent State

    2.1 Why the Context Window Cannot Serve as Memory

    The context window is a short-term workspace, not long-term memory. It is length-limited, cannot be shared across processes, and cannot be queried structurally. Relying on context for memory is equivalent to keeping a database in an in-memory variable: once the process stops, the data is gone.

    2.2 A Minimal, Practical Memory Architecture

    A common industry approach splits memory into three layers:

    • Facts layer: stable user preferences, environment parameters, and secret references (store the reference only, never the plaintext);
    • Events layer: the time of each task, a summary of the input, the execution result, and the failure reason;
    • Summary layer: structured conclusions aggregated from the events layer by day or by week.

    The events layer usually lives in a relational database or an embedded store, which makes timeline-based retrieval straightforward. The summary layer compresses long-term memory so that retrieval does not push massive volumes of raw logs back into the context.

    An illustrative table structure:

    1. CREATE TABLE task_events (
    2. id INTEGER PRIMARY KEY,
    3. ts TEXT NOT NULL,
    4. task_type TEXT NOT NULL,
    5. input_digest TEXT,
    6. result_status TEXT,
    7. error TEXT
    8. );
    9. CREATE TABLE long_term_facts (
    10. key TEXT PRIMARY KEY,
    11. value TEXT,
    12. updated_at TEXT
    13. );

    2.3 The Compounding Effect of Memory

    Once task logs are searchable, the agent has the beginnings of self-learning: it can recall which parameters worked for a similar task last time, which step failed, and which output format the user prefers. As usage accumulates, accuracy on complex workflows improves naturally, because uncertainty is gradually eliminated by historical data. Two engineering cautions apply: first, store only references to sensitive information (injected, for example, by a secrets management service or environment variables); second, define retention periods and redaction policies for memory so that logs do not become a source of risk.

    3. Cost Control: Route Deterministic Tasks to Code, Not to the Model

    3.1 The Root Cause of Runaway Cost

    Token spend spikes usually happen not because the model’s unit price is high, but because deterministic logic has been handed to probabilistic reasoning. Every “read file, decide, write back” loop that calls the model once makes cost grow linearly, or even exponentially, with the number of steps.

    3.2 A Tiered Execution Strategy

    A recommended approach divides tasks into three tiers:

    1. Deterministic tier: format conversion, field extraction, scheduled scraping, and report generation, all handled by scripts;
    2. Judgment tier: classification and summarization that require semantic understanding, which call the model;
    3. Orchestration tier: the agent decides the call order and hardens reusable parts into code.

    A simple pseudocode sketch:

    1. if task.is_deterministic():
    2. run_script(task.script_ref) # zero token cost
    3. else:
    4. plan = llm.plan(task.context) # call the model only where necessary
    5. execute(plan)

    3.3 Model Routing and Fallback

    With a unified multi-model access layer (a common industry pattern is an aggregation gateway or a self-built router), you can select a model tier based on task complexity: a small-parameter model for simple extraction, and an upgrade only for complex reasoning. Set timeout-based fallback and retry limits so that the cost of a single task stays bounded. Note that specific pricing and model capabilities should be confirmed against the public documentation of the service you choose; this article cites no unverified figures.

    4. Always-On at the Edge: Low-Power, Persistent Execution Nodes

    4.1 Why Put the Agent at the Edge

    A cloud instance that runs continuously incurs ongoing charges, whereas an idle old phone or a low-power device can serve as an always-on node at lower cost and is naturally close to the real environment: it can read device sensor state, notifications, and battery information to enable hardware-level automation, such as extracting a one-time verification code and filling it in automatically.

    4.2 Engineering Essentials for Edge Deployment

    • Process supervision: use the system’s built-in process management and scheduled wake mechanisms so the agent recovers automatically after a restart;
    • Network resilience: reconnect after disconnects, make requests idempotent, and queue failures for retry;
    • Least privilege: grant only the permissions required to complete the task, and require a second confirmation for sensitive actions;
    • Local first: generate content on the device first, then distribute it centrally, which reduces unnecessary remote calls and lowers the risk of distribution throttling caused by frequent API calls.

    4.3 Edge-Cloud Collaboration

    The recommended combination is “execution at the edge, memory in the cloud”: the edge handles collection and execution, while the cloud handles long-term storage, summary generation, and cross-device synchronization. This preserves the low cost and real-time nature of the edge while avoiding fragmented memory.

    5. Use a Local Knowledge Base as the Control Panel

    An instant messaging interface is suitable for triggering tasks but not for carrying structured information; the message stream quickly causes information overload. A more reliable approach is to use a local Markdown knowledge base as the “control panel”: the agent writes daily summaries, travel plans, todos, and retrospectives into fixed templates, and the human reviews and edits them directly through the file system.

    Suggested directory layout:

    1. /notes
    2. /daily/2025-01-01.md
    3. /plans/trip.md
    4. /todos/inbox.md
    5. /skills/*.md

    After continuously feeding it for 7 to 20 days, the agent can infer the user’s daily and work rhythm and proactively generate structured summaries instead of passively waiting for questions. Because every artifact is plain text, it is naturally versionable, portable, and auditable.

    6. Skill-Based Thinking: Package Recurring Friction Points into Reusable Capabilities

    One of the core competitive advantages in the AI era is turning recurring friction points in daily life into “skills.” The criteria are simple: does the same type of task occur more than three times a month, does it have stable inputs and outputs, and can it be clearly accepted or verified?

    A skill package should contain four elements: trigger conditions, input contract, execution steps, and acceptance criteria. Take “pairing dishes from what is in the fridge” as an example: the input is the ingredient list plus dietary restrictions, the steps run deterministic filtering first and then call the model to generate combinations, and acceptance requires the output to include executable steps and alternatives. Take “financial statement analysis” as another example: the deterministic tier handles data retrieval and ratio calculation, and the model only explains unusual fluctuations.

    The payoff is freed-up cognitive bandwidth: the human only defines the goal and the acceptance criteria, while repetitive work is handed to reusable skills. If more complex collaboration is needed, you can introduce multi-agent division of labor (planner, executor, reviewer), but always keep a human review gate.

    7. Implementation Checklist

    1. Build memory first: events table + facts table + summary task;
    2. Then add tiering: script the deterministic tasks and let the model handle only semantic judgment;
    3. Add routing: a unified model access layer with fallback and budget caps;
    4. Run always-on at the edge: process supervision, least privilege, retry on disconnection;
    5. Set up the knowledge base panel: fixed templates, plain text, versionable;
    6. Accumulate skills: a four-element template that gradually builds reusable capabilities;
    7. Observability: connect a general-purpose logging service and monitoring with alerting, and set thresholds for cost, success rate, and latency.

    For cloud deployment, you can combine object storage for the knowledge base, a message queue for task buffering, a container platform for always-on services, and a logging and monitoring stack for observability. These are all general product categories; the specific selection should be evaluated against your own compliance requirements and budget.