AI Agent Implementation: Memory, Cost Control, and Deterministic Automation
This article examines five key engineering challenges in moving AI agents from chat demos to production: layered memory and state management, cost optimization through task routing and code-first execution, always-on on-device deployment, using a local knowledge base as a control panel, and packaging recurring workflows as reusable skills. It includes practical schema, pseudocode, and configuration examples, plus a four-stage rollout roadmap and the metrics to use when evaluating each change.
1. Introduction: The Value of Agents Lies in Deterministic Automation
Over the past two years, many teams have connected large language models to a chat interface, only to find a clear gap between “can chat” and “can deliver”: the same instruction has to be issued repeatedly, context is lost midway through long tasks, token consumption grows linearly with each conversation turn, and output is unstable and hard to fit into a production workflow. The industry has gradually converged on a shared view: the real value of an agent is not generating a polished natural-language reply, but turning high-frequency, repetitive, relatively well-defined tasks into deterministic automation that is repeatable, observable, and rollback-capable.
This article takes a general technical perspective and discusses five key engineering problems in agent implementation: memory and state management, cost structure optimization, always-on on-device deployment, a personal knowledge base as a control panel, and skill-based packaging. It does not cover any specific vendor product, and all capability descriptions stay within technically accepted industry practice.
2. Memory Systems: From Stateless Sessions to an Accumulating Execution Entity
2.1 Typical Symptoms of a Memoryless Architecture
Agents without persistent state usually exhibit three problems. First, context resets to zero after every restart, forcing users to re-explain the background. Second, instructions get repeated, because confirmed preferences, credential locations, and directory conventions are asked about again and again. Third, token consumption spikes abnormally, since the full background has to be stuffed back into the context window on every turn.
2.2 Designing Layered Memory
The more robust engineering approach is to split “memory” into three layers:
- Short-term session memory: the working context of the current task, reclaimed when the task ends.
- Task log memory: a structured database (such as an embedded relational database) that records the time, input digest, call chain, result, and error code of each execution.
- Long-term preference memory: stable user conventions, environment paths, and how interface credentials are referenced (store the reference only, never the plaintext).
The illustrative schema can be very plain:
CREATE TABLE task_log (id INTEGER PRIMARY KEY,created_at TEXT NOT NULL,task_type TEXT NOT NULL,input_digest TEXT,action TEXT,result_code INTEGER,latency_ms INTEGER);CREATE TABLE preference (key TEXT PRIMARY KEY,value TEXT,updated_at TEXT);
2.3 How Memory Translates into Accuracy
The value of memory is not “remembering more” but “reducing uncertainty.” Once the task log accumulates enough volume, the agent can apply retrieval augmentation to similar tasks: look up successful historical paths first, then decide whether model inference is actually needed. This yields three direct benefits: repetitive tasks can take a cached path, failure modes can be measured and avoided, and prompts can converge automatically against the preference store, significantly shortening input length. It is worth stressing that credential information should be handled through secret references or a secret management service, so plaintext never lands in the database.
3. Cost Governance: Let the Model Handle Only What Requires Judgment
3.1 Root Causes of Runaway Cost
The common root cause of high cost is not unit price but call structure: deterministic logic is handed to the model for turn-by-turn reasoning, so a single task is split into dozens of round trips; at the same time, every request is routed to the strongest model, with no strategy for tiering by complexity.
3.2 Three Reusable Cost-Reduction Principles
First, tiered task routing. Simple classification, format conversion, and field extraction go to lightweight models or a rules engine; only tasks that need long-chain reasoning are escalated to a high-capability model. In practice, a unified gateway can handle model routing while preserving the ability to switch and fall back.
Second, code-first. For deterministic tasks, have the agent generate a script once and let the runtime execute it, instead of continuing an open-ended conversational loop. Batch file renaming, report field alignment, and log aggregation statistics all fit a “generate once, reuse many times” code path.
# Pseudocode: deterministic tasks take the code path, avoiding per-turn model callsdef handle(task):if task.type in DETERMINISTIC_TASKS:script = agent.generate_script(task.spec) # generated only oncereturn runtime.run(script, task.payload) # reused afterwardsreturn llm.route_by_complexity(task) # only complex tasks reach the model
Third, context compression and caching. For long documents, produce a structured summary and a chunk index first, then recall only the fragments needed; for repeated prefixes, reuse cached content to cut duplicate billing.
One practical engagement gave a sense of scale: after introducing tiered routing and code-based execution, model spend under the same task load dropped by an order of magnitude. No absolute numbers are given here, because actual gains depend heavily on task composition and model pricing, and readers should run canary measurements on their own workloads.
4. Always-On On-Device: A Low-Power, Persistently Available Execution Node
4.1 Why Consider the Device Side
Always-on cloud instances require continuous billing and operations, while on-device hardware naturally offers “low marginal cost, close to the real environment.” Running an agent runtime inside a terminal emulation environment on an everyday mobile device gives access to context such as sensors, notifications, battery level, and local files, enabling hardware-level automation — for example, automatically reading and processing one-time passcode notifications, or adjusting task frequency based on battery state.
4.2 Engineering Constraints of On-Device Deployment
An on-device approach has to face its constraints: device sleep interrupts processes, so wake strategies and a task queue are needed; local storage is limited, so logs must be rotated and cleaned up; unstable networks require tasks that can resume from a checkpoint. The recommended structure is “on-device collection and execution + cloud scheduling and storage,” with the device keeping only a minimal runtime and logs and state syncing asynchronously to object storage or a logging service.
# On-device task scheduling exampleschedule:- name: collect_contextcron: "*/30 * * * *"on_battery_below: 20% -> skip- name: sync_logscron: "0 * * * *"retry: 3backoff: exponential
4.3 Compliance and Risk Notes
Running publishing scripts directly on a device can indeed bypass some platform interface restrictions, but it also raises account risk-control and compliance exposure. The safer approach is to prefer official open APIs, limit automation to the user’s own data and own accounts, and keep a complete audit trail of operations.
5. Using a Local Knowledge Base as a Control Panel
5.1 A Chat Window Is Not a Good Control Plane
Instant messaging interfaces are fine for triggering tasks but poor at holding structured information: the message stream is time-ordered, retrieval is weak, and it is hard to build reusable knowledge assets.
5.2 A Local-First Knowledge Base Design
A more sensible design is to have the agent write its output back into a local Markdown knowledge base: daily summaries, to-dos, travel plans, and financial records each occupy a directory, with backlinks and tags forming a navigable structure. The agent handles three things: scheduled collection, structured writing, and conflict merging.
vault/daily/2025-01-08.mdtasks/inbox.mdprojects/travel-plan.mdfinance/2025-01.md
Writes should follow a convention: frontmatter records the source and timestamp, the body uses stable heading levels, and changes are appended rather than overwritten, so version control and retrospection stay possible. After feeding it continuously for two to three weeks, the agent’s model of the user’s rhythm becomes noticeably more accurate, and it can proactively generate a weekly report, spot a pile-up of to-dos, and flag abnormal spending.
6. Skill Packaging: Turning Recurring Friction into Reusable Capabilities
The test for whether to package a skill is simple: does this happen repeatedly, does it have stable inputs and outputs, and is it worth retaining? Monthly financial statement organization, meal planning from what is already in the fridge, archiving meeting notes, and competitor monitoring all meet the criteria.
A practical skill contract has four parts: trigger conditions, input schema, execution steps, and acceptance criteria.
{"skill": "fridge-meal-plan","trigger": "manual | weekly","input": {"ingredients": "list<string>", "constraints": "enum"},"steps": ["normalize", "match_recipes", "render_markdown"],"acceptance": "output contains >=3 dishes and shopping diff"}
The real payoff of skill packaging is freeing up cognitive bandwidth: once the decision flow is fixed, the human judges only at key checkpoints. To add a methodological layer of constraint, a mature startup decision framework can be abstracted into a review checklist and the agent can interrogate each item in turn rather than handing over a conclusion directly.
7. Rollout Roadmap and Metrics
A four-stage progression is recommended. Stage one: build the task log and preference store, so state is persisted first. Stage two: add tiered model routing and code-based refactoring to drive cost down. Stage three: connect the local knowledge base to produce structured output. Stage four: accumulate the skill library and run canary evaluations.
Metrics should cover four dimensions: task success rate, human intervention rate, cost per task, and average latency. Compare every change against a small traffic slice, and avoid the trap of “looking smarter while actually being more expensive and slower.”
8. Conclusion
The focus of agent engineering is shifting from prompt technique to systems engineering: state must persist, execution must be deterministic, cost must be tiered, output must be structured, and capabilities must be reusable. On a general cloud environment, combined with foundational capabilities such as object storage, message queues, container platforms, logging services, and monitoring and alerting, you can build a stable and controllable runtime foundation for agents. Baidu AI Cloud offers a complete product portfolio in these general engineering areas and can serve as a reference foundation for building your own automation system.
