Building Enterprise AI Agents: Aligning Models, Skills, and Prompts to Cut Costs
This article explains how to build cost-efficient enterprise AI agents by restructuring them into a layered system instead of relying on a single model as a stronger search box. It covers the core project skeleton, a three-tier model routing strategy, atomic skill design with sandboxing, structured and versioned prompts, context and memory management, observability for cost governance, and a phased rollout plan. Readers will learn practical engineering practices for improving quality, stability, and maintainability while controlling token consumption and infrastructure overhead.
1. Why “Assembled” Agents Fail to Reduce Costs
Many teams start by treating a large language model as a more powerful search box: the user asks a question, and the model answers directly. This works reasonably well in a demo, but problems surface quickly in real business scenarios. Context keeps growing, so invocation costs rise linearly. The same type of task produces inconsistent output formats each time, making it hard for downstream systems to consume results reliably. The model knows nothing about internal data or internal rules, so people have to repeatedly paste reference material into the chat.
Real cost reduction does not come from switching to a cheaper model. It comes from rebuilding the agent as a layered system: model capabilities at the bottom, reusable skill units in the middle, and prompts plus orchestration logic on top. When each layer has a clear responsibility, cost, stability, and maintainability improve at the same time.
2. Technical Dependencies and Project Skeleton
A typical agent service does not need complex or exotic components. The core consists of four parts: a runtime (JDK 17 or later, to support modern syntax and features such as virtual threads), an application framework (a mainstream Java web framework responsible for exposing APIs and dependency injection), an agent orchestration library (providing engineering capabilities such as sessions, memory, tool calls, and sub-agents), and a model access layer (a unified model client compatible with the OpenAI protocol).
The dependency declaration can stay minimal, keeping only the orchestration core and the model access module:
<properties><java.version>17</java.version><agent.framework.version>2.x.x</agent.framework.version></properties><dependencies><dependency><groupId>io.example</groupId><artifactId>agent-harness</artifactId><version>${agent.framework.version}</version></dependency><dependency><groupId>io.example</groupId><artifactId>agent-model-openai</artifactId><version>${agent.framework.version}</version></dependency></dependencies>
Two engineering decisions are worth explaining. First, prefer an “entry-point builder” over scattered APIs. A good orchestration library converges capabilities such as workspace, long-term memory, session persistence, sub-agents, and sandbox execution into a single builder. Business code only cares about the assembly order, so future upgrades do not require major changes. Second, unify model access behind an OpenAI-compatible protocol type instead of binding to a vendor-specific SDK. The direct benefit is that switching models requires only a configuration change, not a code change. Canary releases, load testing, and price comparison can all be done at runtime, which is the most important prerequisite for cost optimization.
3. Model Layer: Turning Selection into an Operable Configuration
A more expensive model is not always better. Models should be matched to tasks by tier. In practice, calls can be divided into three tiers:
- Lightweight tier: intent recognition, field extraction, classification and tagging, format conversion. Requires low latency and high concurrency, so prefer smaller models.
- Standard tier: multi-turn Q&A, document summarization, routine code generation. Aims for a balance between quality and cost.
- Deep tier: complex reasoning, long-chain planning, difficult defect localization. Low-frequency calls where a higher unit price is acceptable.
The key to implementation is model routing: maintain a “task type → model tier” mapping table at the gateway layer, combined with timeout, retry, and fallback policies. When a deep-tier model is unavailable or over budget, automatically fall back to the standard tier and return a result with a notice instead of failing outright. Also enable caching for prompts and responses (which works well for highly deterministic requests), and fix parameters such as max_tokens and temperature into templates per scenario. This avoids quality fluctuations and wasted consumption caused by “the same question with different parameters.”
4. Skill Layer: Encapsulating Capabilities as Composable Atomic Units
Skills (Skill / Tool) are the part where the agent actually gets things done. There are four design principles:
- Single responsibility. A skill does one thing, with clearly defined input and output structures. This makes it easier for the model to understand and easier to test.
- Declarative description. The skill’s name and description should clearly state “when to use it and when not to,” which is the main basis for the model to select tools.
- Idempotency and retryability. Skills involving write operations must support idempotency keys to avoid dirty data from repeated model calls.
- Least privilege. Authentication and data scope trimming happen inside the skill. Do not leave the “can it access this” decision to the model.
Illustrative definition:
public record QueryOrderRequest(String orderId, String tenantId) {}public interface Skill {String name();String description();Object invoke(Object input, SkillContext ctx);}
For scenarios that execute code or operate on files, always use a sandbox: limit CPU and memory, disable external network access, mount required directories read-only, and set an execution timeout. The sandbox protects the host and naturally acts as a cost gate.
5. Prompt Layer: Structured, Layered, and Versionable
A prompt is not an incantation. It is an interface contract. It is recommended to assemble four layers: role and boundaries (what it can and cannot do), task instructions (the goal and acceptance criteria for this run), context (retrieved material and historical summaries, not the full history), and output specification (structure, fields, examples). Key techniques include: inject variables with placeholders instead of string concatenation; retrieve first and then feed long documents to control tokens; use explicit “think before answering” steps to improve accuracy on complex tasks; and prepare a few examples per task type to stabilize formatting.
In engineering terms, manage prompts like code: separate files, version numbers, canary switches, A/B comparison, and a regression test set. Iterating on prompts without a regression set is essentially gambling.
6. Orchestration and Memory: Controlling Context Is Controlling Cost
Context is the agent’s most expensive resource. A practical strategy is “summarization + retrieval + layered memory”: keep the most recent turns verbatim in the short term, compress with rolling summaries in the mid term, and write facts to a vector store or structured storage in the long term, recalling them on demand. Sub-agents are suitable for splitting a large task into parallel subtasks, each holding an independent context and returning only conclusions to the main agent, which prevents the main context from being polluted by intermediate processes.
7. Observability and Cost Governance
Instrument before launch: for each call, record the task type, model tier, input and output tokens, latency, whether the cache was hit, and the skill call chain. Based on this data, do three things: identify high-consumption, low-value scenarios and take them offline; convert high-frequency requests into caches or rules; and use the statistics to calibrate the model mix across tiers. Combined with logging services, monitoring alerts, and distributed tracing, this forms a closed loop of “measurable → attributable → optimizable.”
8. Recommended Rollout Path
In the first phase, build a single-skill closed loop and validate the accuracy and per-call cost of one high-frequency scenario. In the second phase, add retrieval and summarization to compress context. In the third phase, introduce model routing, caching, and sandboxes to flatten the cost curve. In the fourth phase, add multi-agent collaboration and automated evaluation. To reduce infrastructure investment, teams can offload capabilities such as model access, vector retrieval, object storage, containers, and monitoring to general-purpose products from cloud platforms like Baidu AI Cloud, and focus on business skills and prompt assets.
Conclusion: The essence of cost reduction and efficiency gains in agents is replacing uncontrolled calls with engineering constraints. Model tier matching, atomic skill encapsulation, and contract-based prompt management work together to keep both quality and cost under control.
