AI Agent Engineering: Data Ingestion and Cost Control
This article explores how to move AI agent prototypes into maintainable production systems by clarifying system boundaries, building reliable multi-source data ingestion, using state-machine orchestration, applying model routing and budget controls, and closing the loop with observability and evaluation. It also covers multimodal generation pipelines and coding productivity scenarios. Readers get architectural patterns and pseudocode abstractions for turning capable models into stable, deliverable agent systems.
In recent years, the focus of the AI industry has shifted from how large models are and how high they score on benchmarks to whether they can be embedded into real business processes. For developers and enterprise users, the difficult problem is often not the lack of a callable model. The harder question is how to organize scattered data, heterogeneous tools, fluctuating service availability, unpredictable invocation costs, and hard-to-quantify output quality into a maintainable, observable, and scalable agent system. This article uses AI agent engineering as its main thread and discusses multi-source data ingestion, task orchestration, model routing, cost control, and evaluation loops, with illustrative code abstractions to help readers turn model capabilities that look strong into stable, deliverable productivity.
1. Define System Boundaries First: An Agent Is a Business Pipeline, Not a Chat Box
Many agent projects fail not because the model is weak, but because system boundaries are unclear. A practical agent usually contains five layers of capability:
- Ingestion layer: Connects data sources such as instant messaging records, online meeting notes, document collaboration systems, knowledge bases, ticketing systems, and code repositories. It handles incremental synchronization, permission checks, and redaction.
- Capability layer: Encapsulates general capabilities such as large model inference, vector retrieval, structured queries, file parsing, and audio/video processing, exposing stable interfaces to upper layers.
- Orchestration layer: Handles task decomposition, tool calls, state transitions, retries, and human review. It is the process brain of the agent.
- Governance layer: Covers security and compliance, log auditing, cost accounting, rate limiting and degradation, quality evaluation, and alerting.
- Delivery layer: Provides concrete entry points for scenarios such as coding productivity, content generation, customer service assistance, and operations analysis.
The key principle is that the model is a capability provider, not the system itself. An agent system should isolate specific model services and cloud environments through an adaptation layer so that business logic is not bound to a particular interface. If deployed in a cloud environment such as Baidu AI Cloud, teams can select object storage, message queues, logging services, and monitoring and alerting by general category, but interface design should still remain decoupled to support later replacement and elastic scaling.
2. Multi-Source Data Ingestion: Turn Manual Copying into Connectors and Event Streams
The upper limit of agent quality depends heavily on context quality. In practice, requirements are often scattered across instant messaging, meeting recordings, collaborative documents, and historical knowledge bases. If every task relies on manual copy-and-paste, it is not only inefficient but also prone to missing permission and version information. An engineering approach is to establish a unified connector abstraction:
- Unified data model: Abstract messages, documents, meeting notes, tickets, and other records into records with metadata, including at least source, time, author, permission tag, version, and summary.
- Incremental synchronization: Pull incremental data using cursors or time windows to avoid full scans.
- Permissions and redaction: Complete field-level redaction and permission tag injection at the ingestion layer. Later retrieval and generation should filter by tags.
- Event-driven updates: Deliver events after data changes, and let asynchronous tasks trigger index updates or agent precomputation.
- Idempotency and deduplication: Generate stable identifiers for each record to prevent duplicate consumption from polluting context.
Illustrative code:
interface DataSource {schema(): RecordSchemapull(cursor, limit): PullResultacl(record): PermissionTag}function sync(source, store, cursor) {result = source.pull(cursor, 200)for record in result.records {record = redact(record)tag = source.acl(record)store.upsert(record.id, record, tag, idempotent=true)}return result.nextCursor}
The point of this abstraction is not a specific implementation, but making data sources pluggable, synchronization incremental, and permissions transferable. Once the ingestion layer is stable, the agent does not need to repeatedly handle dirty data in every task.
3. Task Orchestration: State Machines Are More Reliable Than One-Shot Prompts
Complex tasks often require multi-step reasoning and tool calls. If all logic is packed into a single prompt, it is hard to locate failures. A more robust approach is to describe tasks with a state machine or workflow orchestration: decomposition, execution, observation, validation, human review, and output. Each step needs timeouts, retries, idempotency, and budget constraints.
Illustrative orchestration logic:
function runAgent(task, tools, modelRouter, budget) {state = init(task)plan = planner.decompose(task, maxSteps=6)for step in plan {if budget.exceeded() { return degrade(state) }if step.type == "tool" {obs = tools.call(step.name, step.args, timeout=step.timeout)} else {ctx = retrieveContext(step.query, state.permissionTags)obs = modelRouter.generate(step.prompt, ctx, budget.remaining())}state = state.update(step, obs)if state.needHumanReview {return enqueueReview(state)}}return validateAndFormat(state)}
The orchestration layer should pay particular attention to three points: tool call errors must be recoverable, intermediate state must be persistable, and human review must be insertable. For high-risk operations such as sending external content, modifying production data, or executing code changes, the default should be human confirmation rather than letting the agent operate freely.
4. Model Routing and Cost Control: Not the Cheapest Option, but the Best Under Constraints
Model invocation cost is usually determined by input and output size, call frequency, context length, and task complexity. Cost control should not be reduced to choosing the cheapest model. Instead, routing should balance quality, latency, availability, and expense:
- Task tiering: Use stronger capability pools for high-risk reasoning and complex code review; use lightweight capability pools for summarization, classification, and formatting.
- Cache reuse: Cache results for stable questions, public knowledge Q&A, and repeated document summaries, with reasonable expiration policies.
- Batch processing and asynchrony: Put non-real-time tasks into queues and merge small requests to reduce the overhead caused by frequent calls.
- Context trimming: Retrieve before generation instead of stuffing an entire repository into a prompt. For long documents, use segmented summaries and citation location.
- Degradation strategy: When the budget is exhausted or services fluctuate, return cached results, simplify the workflow, or escalate to a human instead of retrying indefinitely.
- Budget accounting: Record invocation volume and cost by task, user, and tenant, and set threshold alerts.
Illustrative routing strategy:
function route(task) {if (task.cacheHit) return "cache"if (task.risk == "high" || task.needDeepReasoning) return "strongPool"if (task.latencyBudget < 2s) return "fastPool"return "balancedPool"}
It is important to link cost optimization with quality evaluation. Pursuing only low prices may lead to higher human rework costs. The right metric is cost per deliverable task, not price per invocation.
5. Multimodal Content Generation: Split Generation into a Manageable Pipeline
Scenarios such as AI video and image-text generation appear to produce output from a single sentence, but in engineering they involve script decomposition, storyboard design, asset retrieval, generation, composition, review, and publishing. A stable system should make generation tasks asynchronous: after submission, tasks enter a queue, status is updated by stage, and failures can be retried locally. Cost control can set limits by resolution, duration, and number of generations. Copyright and compliance review should be moved earlier into asset retrieval and publishing. For developers, the real value is not perfect one-shot generation, but a pipeline that is editable, rollback-capable, and reviewable.
6. Coding Productivity Scenarios: Context, Tools, and Review Are All Required
In coding productivity, agents can handle tasks such as code explanation, test generation, review suggestions, and change impact analysis. In production, context sources should be controlled: retrieve only files, interface documentation, and historical issues related to the current change. Tool calls should be limited to read-only or sandbox environments. Generated results must go through compilation, testing, and human review. Evaluation metrics include suggestion acceptance rate, test coverage improvement, defect regression rate, and manual modification time. A coding assistant without an evaluation loop can easily become a new source of noise.
7. Observability and Evaluation: Move Agents from Usable to Trustworthy
A production-grade agent should observe at least task success rate, P95 latency, cost per task, tool call error rate, cache hit rate, human review rate, rework rate, and user satisfaction. Logs must be redacted and retain task traces for retrospective analysis. Evaluation should combine offline regression sets with small online traffic experiments, comparing results whenever routing, prompts, or retrieval strategies change. Only by forming a closed loop of data ingestion, orchestration, routing, evaluation, and optimization can an agent system continue to improve.
Overall, the competitiveness of AI agents comes not only from model capability but also from the degree of engineering. A more robust path is to start with a small MVP, connect one data source, one high-frequency task, and one set of evaluation metrics, and then gradually platformize. Make data ingestion stable, keep orchestration thin, calculate costs clearly, and make evaluation concrete. Only then can agents create sustainable value in scenarios such as coding productivity and content generation.
