AI Agent in Practice: Five Core Engines and Cost Governance
This article explains why AI agents often underperform despite using the same foundation models, and presents an engineering approach built around five capability engines: identity and memory, perception, expression, efficiency and cost, and ecosystem navigation. It covers layered memory design, controlled retrieval tool interfaces, asynchronous multimodal tasks, token observability and budget alerts, plus a phased rollout path, evaluation metrics, and risk controls for prompt injection and unauthorized tool use.
1. Problem Framing: Why “Install and It Just Works” Is Often an Illusion
Many teams reach a counterintuitive conclusion after adopting an agent framework: with the same underlying model and orchestration framework, final results vary widely across teams. The cause is usually not the model itself, but whether the surrounding context supply, tool boundaries, and cost control system are complete. This is similar to handing over a house: the gap between a bare shell and a fully finished home is not structural, but comes from systematically completing plumbing, electrical, HVAC, and interior work.
Four common symptoms are highly consistent:
- Context is lost after a session ends, so users must restate the background repeatedly;
- External real-time information cannot be retrieved, and answers stay within the model’s internal knowledge;
- Output forms are limited to text, making it hard to cover image and voice scenarios;
- Token consumption is unpredictable, and repeated retries across long tool chains cause bills to spiral.
These four points map to four capability lines: memory, perception, expression, and efficiency. The following sections provide engineering solutions for each.
2. General Design of the Five Core Capability Engines
1. Identity and Memory Engine
The identity layer addresses “role drift.” The engineering recommendation is to separate persona settings, responsibility boundaries, and output specifications from the main prompt into an independent, versionable configuration file, managed through version control for review and rollback. An example structure:
# role.md- Role: Backend architecture review assistant- Responsibilities: Review API design, capacity, and observability plans- Boundaries: Do not output production change commands; provide suggestions only- Output: Conclusion + risk list + actionable improvements
The memory layer should be designed in tiers: short-term memory holds the current session window; episodic memory holds task conclusions and user preferences; semantic memory holds reusable domain facts. In practice, combine vector retrieval with structured storage. Compress via summarization before writing, weight by relevance and recency when reading, and set retention periods and deletion mechanisms to meet compliance requirements.
def build_context(query, user_id, k=5):short = session_window(user_id, limit=8)long = vector_store.search(query, top_k=k, filter={"user": user_id})return compress(short) + "\n" + render(long)
2. Perception Capability Engine
The key to the perception layer is not “being able to get online,” but getting online in a controlled way. Abstract a unified retrieval tool interface that hides differences in underlying implementations, and build allowlisted domains, rate limits, timeouts, and failure backoff into the tool layer. For pages that require interaction, prefer official APIs; use a headless browser only when necessary, and clearly respect the target site’s terms of service and access frequency constraints.
The quality of tool descriptions directly determines invocation accuracy. Descriptions should state the applicable scenarios, input and output structures, and failure semantics, avoiding misselection among similar tools.
3. Expression Capability Engine
Multimodal capabilities should be integrated as a separate capability domain: speech transcription for input-side noise reduction and structuring, speech synthesis for accessibility scenarios, and image generation for diagrams and draft assets. The engineering focus is asynchrony: decouple time-consuming tasks through a message queue, have the frontend return a task identifier first, then obtain results via callback or polling, avoiding long-lived connection occupancy and timeout cascades.
4. Efficiency and Cost Engine
Cost governance requires observability first. Log the model, input and output lengths, tool latency, and retry count for each call to form an aggregable usage view, then set budgets and alert thresholds accordingly. Common measures include: keeping prompt prefixes stable to leverage caching, truncating and deduplicating retrieval results, structurally trimming tool outputs, and assigning low-risk tasks such as classification and extraction to smaller models.
if est_tokens(payload) > BUDGET:payload = truncate_middle(payload, keep_head=1000, keep_tail=500)
Note that actual cost reduction ratios depend heavily on task shape and implementation quality. Do not assume fixed numbers; rely on your own load test data.
5. Ecosystem Navigation Engine
Once roles, tools, and knowledge bases grow in number, retrieval-based navigation is more sustainable than exhaustive registration: build tags and applicability descriptions for each capability, recall candidate capabilities semantically at runtime, then let the model choose, which significantly reduces the extra overhead caused by prompt bloat.
3. Phased Rollout Path
- Phase one: solidify role configuration and basic memory, and verify cross-session continuity;
- Phase two: integrate a unified retrieval tool layer to add real-time information capability;
- Phase three: introduce asynchronous multimodal task pipelines;
- Phase four: build a usage dashboard and budget alerts to close the cost loop;
- Phase five: accumulate a capability catalog and evaluation set, and use fixed test cases to regression-test every change.
4. Evaluation and Risk Control
Build a three-layer evaluation: tool invocation accuracy, task completion rate, and cost per task. Any configuration change should be compared on the same evaluation set to avoid “tuning by feel.” Also watch for prompt injection, unauthorized tool invocation, and sensitive data leakage risks: annotate the source of external content and isolate instructions, and keep a human confirmation step for high-impact operations.
5. Conclusion
The capability ceiling of an agent depends on whether memory is continuous, perception is controllable, expression is complete, and cost is measurable. Engineering these four lines, combined with continuous evaluation, is what moves an agent from demo to stable production. If running in a cloud environment such as Baidu AI Cloud that offers general capabilities like container platforms, message queues, object storage, and monitoring and alerting, the components above can be mapped to managed services, reducing the burden of infrastructure maintenance.
