AI Agents That Take Action: Execution Pipeline, Cost, and Governance Explained
An AI agent is not a new kind of large language model but an execution shell that layers tool calling and loop control on top of a general model, letting it act on files, browsers, command lines, and business APIs. This article explains a minimal four-layer agent architecture—perception, planning, execution, and memory/recovery—then traces a concrete task from intent parsing all the way to archival. It analyzes why agent token costs grow roughly quadratically with loop length, catalogs the failure modes that dominate production, and covers permission isolation, sandboxing, auditing, observability, and evaluation. It closes with a staged rollout strategy that starts with read-only tasks and gradually opens higher-risk actions. Readers come away with a practical engineering view of building, costing, and governing action-capable AI agents.
1. First, the Concepts: A Shift in the Capability Boundary
Over the past two years, the dominant form of large language models has been conversation: users ask a question, the model outputs text or code snippets, and the remaining actions are still done by people. If you hand it a request like “clean up this spreadsheet for me and then email it to my boss,” it can suggest a cleaning approach and even a script, but the spreadsheet stays on your hard drive and the email never sends itself. What the so-called “AI agent” fills in is exactly this gap—on top of the model, it wraps a mechanism of tool calling and loop control, so that the structured instructions the model emits can actually act on the file system, browsers, command lines, and various business APIs.
It is worth stressing that an agent is not a new generation of large model. It is more like an “execution shell”: underneath it still calls a general-purpose large model for understanding and reasoning, and the real technical increment comes from three things outside the model—how context is organized, how actions are orchestrated, and how results are verified. Understanding this is what makes the cost and security analysis that follows meaningful.
2. A Minimal Viable Architecture: The Four Layers of an Agent
1. The Perception Layer: Tool Definitions and Context Assembly
An agent’s capability ceiling is determined by what it can “see” and what it can “call.” Each tool needs to declare its name, parameters, return-value semantics, and side-effect level in a machine-readable schema, for example:
{"name": "send_email","description": "Send a plain-text email to the specified recipients","parameters": {"type": "object","properties": {"to": { "type": "string" },"subject": { "type": "string" },"body": { "type": "string" },"attachments": { "type": "array", "items": { "type": "string" } }},"required": ["to", "subject", "body"]},"x-side-effect": "irreversible","x-requires-approval": true}
The wording of a tool description directly changes the model’s selection behavior. This is a classic “the prompt is the interface” problem: vague descriptions lead to the wrong tool being chosen or to parameter hallucination.
2. The Planning Layer: Task Decomposition and State Machines
An agent does not produce one long answer in a single pass; instead it runs a “think–act–observe” loop (commonly known in the industry as a ReAct-style loop): in each round the model decides the next action, the execution result is written back into the context, and then the next round begins. A more robust practice in production is to wrap the free-running loop in an explicit state machine: the task is broken into sub-steps with determinable completion states, each with clear inputs, expected outputs, and acceptance conditions, which prevents the model from gradually drifting off target over a long loop.
3. The Execution Layer: Taking Actions and Verifying Results
When a tool returns, its result must be verified rather than trusted unconditionally. Verification should include at least three kinds of checks: output existence and format (was the file generated, do the column counts match expectations, is the encoding correct), semantic soundness (is the amount negative, is the date out of range), and side-effect confirmation (did the email enter the send queue and return a message ID). If any check fails, the error message should be fed back to the model along with the context to start a retry, with an upper limit on retries.
4. The Memory and Recovery Layer
A single task’s context can easily reach tens of thousands of tokens, while both the context window and cost are limited resources. In engineering practice this is usually handled with externalized storage: intermediate artifacts are written to disk or object storage, long-range memory is written to a vector or key-value store, and task checkpoints are written to persistent state, so that a long task can resume after a process restart or a model switch.
3. Tracing One Instruction Through the Full Pipeline
Taking “clean the spreadsheet and email it to my boss” as an example, a usable execution path looks roughly like this:
- Intent parsing and clarification: Identify the input file, the cleaning rules (deduplication, missing-value filling, field standardization), and the recipient. When rules are unclear, ask proactively rather than guessing and running all the way to the end.
- Environment probing: List directories, read the header and the first few rows, check the data volume and encoding, and form an initial understanding of the data.
- Agreeing on the plan and artifacts: Generate the script and test-run it on a copy first; flag risk points for irreversible steps (overwriting the original file, sending externally).
- Execution and self-check: Compute row counts, missing-value rates, and outlier distributions before and after cleaning, and compare them rule by rule against expectations.
- Human confirmation gate: For an outbound action like sending email, use a “dry run + confirm” approach—first output the email body, recipient, and attachment list, and only execute after a person confirms.
- Archiving: Save the script, logs, intermediate artifacts, and the final version to form a reproducible task record.
The value of this pipeline is not how clever any single step is, but that every step has a checkable artifact.
4. Why It Costs So Much: The Token Amplification Effect
Agents burn money not because “the model is expensive,” but because the context is read over and over. Let the prompt length per round be P, the newly added output per round be O, and the total number of rounds be N. Then the total consumption is approximately:
Total ≈ N × P + (N × N / 2) × O
The first term grows linearly; the second grows quadratically, because each round brings the output of all previous rounds back into the context. A fifteen-round task like “read the spreadsheet—write the script—hit an error—fix the script—rerun—send the email” can consume one to two orders of magnitude more tokens than an equivalent conversational interaction. Automatic retries after a failed task can further double the cost. So a number like “a few hundred a day” is not mysterious—it is simply the natural result of a long loop multiplied by the number of retries.
The corresponding optimizations follow naturally:
- Context compression and summarization: Solidify conclusions as each sub-step completes and discard process noise, rather than rolling the entire history forward;
- Layered model strategy: Use more capable models for planning and code generation, and hand deterministic sub-tasks like format conversion and field classification to smaller, faster models—or hardcode them as scripts;
- Tool-return trimming: Have tools return only a structured summary instead of entire blocks of raw data, with paginated reads when necessary;
- Budget guards: Explicitly cap the number of steps and spend inside the loop, and abort and report once the limit is exceeded.
def run_task(task, tools, budget_steps=25, budget_cost=2.0, max_retry=2):spent, step = 0.0, 0while step < budget_steps and spent < budget_cost:step += 1action = planner.decide(task.state, tool_schemas)if action is None:return task.state # converged: task done or clarification neededspent += planner.estimate_cost(task.state)result, ok = executor.invoke(action, tools)if not ok:action.retry += 1if action.retry > max_retry:raise TaskAborted(action, result)task.state.observe(action, result) # feed back after verification, not blind trustraise BudgetExceeded(step, spent)
5. In the Real World, the Enemy Is Failure Modes, Not Model Intelligence
In production, failures are highly concentrated and worth listing separately: parameter hallucination (fabricating field names or paths that do not exist), path and encoding issues (cross-platform separators, Chinese character encoding), goal drift in long loops (by step seven the original constraints have been forgotten), environment inconsistency (runs locally but the sandbox is missing dependencies), missing idempotency (retries causing duplicate sends or duplicate writes), and external API rate limiting and timeouts. The first three are mitigated by constraints and acceptance conditions; the latter three must be handled with engineering means: design an idempotency key for every tool with side effects, and prepare backoff retries and circuit breaking for external calls.
6. Permissions, Sandboxing, and Auditing: Keeping Risk Caged
An agent that can operate your computer is essentially an automated program that has been granted permissions, and its security design cannot rely on “reminding it to be careful in the prompt.” Four practical layers:
- Capability isolation: Run in a separate container or VM, mounting only the directories required to complete the task, and prohibit access to credential directories and system-level configuration;
- Least privilege: Inject credentials on demand through a key management service, issue them with short lifetimes, and revoke them when the task ends—never write them into scripts or logs;
- Tiered approval for side effects: Let read operations run freely; require confirmation for writes and overwrites; force manual sign-off for outbound sends, deletions, and actions involving funds or permission changes, and require that they be traceable;
- Full auditing: Record every step’s action, parameters, return value, duration, and cost; deliver logs centrally to a logging service and connect them to monitoring and alerting, with threshold alerts on anomalous step counts, failure rates, and per-task cost.
In addition, “how much data it can see” is also a risk surface. If a task involves sensitive fields in a spreadsheet, desensitization or field trimming should be completed before the data enters the model context.
7. How to Prove It Works: Observability and Evaluation
An agent is a probabilistic system and cannot be accepted with “one impressive demo.” It is recommended to build three layers of evaluation: a unit layer that verifies the correctness and error handling of a single tool call; a process layer that runs complete tasks on fixed datasets and measures first-pass success rate, average number of steps, and average cost; and a regression layer that accumulates real production failure samples into a case set and automatically reruns them after a model or prompt change, to prevent capability regression. Metrics should include at least task completion rate, human-intervention rate, average per-task cost, and end-to-end latency—these four often conflict with one another and need to be explicitly traded off by business priority.
8. Rollout Recommendations
Do not start from “fully automatic.” A workable progression is: first use agents for read-only tasks (data analysis, report generation, code-base inspection) to build reliability and cost baselines; then open up internally reversible write operations; and only then gradually connect outbound and high-risk actions, always keeping a human sign-off gate and a one-click kill switch. On the infrastructure side, general-purpose cloud capabilities can be combined as needed to carry these requirements: a container platform or serverless compute provides isolated runtimes, a message queue handles long-task asynchrony and peak shaving, object storage keeps intermediate artifacts and versions, a logging service with monitoring and alerting ensures observability, and a key management service manages temporary credentials. On Baidu AI Cloud, these capabilities all fall under the general-purpose cloud product category and can be flexibly combined by business scale, rather than bound to a single form.
Conclusion
The gap between “able to act” and “able to chat” lies not in the model’s parameter count but in engineering completeness: whether the tool contracts are clear, whether state is recoverable, whether results are verified, whether permissions are constrained, and whether cost is guarded. Only when all five are in place does an agent turn from a demo into real productivity; miss any one of them, and it is just a more expensive, harder-to-debug automation script.
