Agent Engineering in Practice: A Guide to Building Production-Ready AI Agents
This article explains how to engineer AI agents for real production environments rather than controlled demos. It covers task decomposition into executable graphs, tool orchestration with least privilege, state management for resumable workflows, subgraph design and multi-agent collaboration, durable execution with fault tolerance, and observability with continuous evaluation. Readers will find practical structures, code examples, and a deployment checklist for moving agents from demo quality to operable systems.
1. Why Agents Need Engineering
Early agent demos usually relied on a linear call chain: receive input, build a prompt, call the model, return the result. This structure works well in controlled environments, but problems surface quickly in real business scenarios: vague task boundaries make the model probe repeatedly, unconstrained tool calls produce side effects, long-running workflows fail midway with no recovery, and multiple agents calling each other create loops that are hard to trace. The core goal of engineering is to wrap the uncertain capability of “the model can reason” inside deterministic processes, state, and governance mechanisms.
You can self-check whether an agent solution is engineering-mature with four questions: Is the process describable? Is the state recoverable? Is the behavior observable? Is the outcome evaluable? If any one is missing, the system stays at the demo stage.
2. Task Decomposition: Turning Vague Goals into an Executable Graph
Task decomposition is not about letting the model “think before answering.” It converts a high-level goal into execution units with dependencies. A three-layer structure is recommended in practice:
- Goal layer: define success criteria and constraints, such as output format, latency budget, and the range of resources that can be called.
- Plan layer: break the goal into ordered steps, marking the input artifacts and acceptance method for each step.
- Execution layer: each step maps to one controlled action, usually a model inference or a single tool call.
Decomposition quality depends on two things. First, granularity: steps that are too coarse force a single step to carry too much uncertainty, while steps that are too fine amplify call overhead and cumulative error. Second, decidability: every step should have a clear completion signal instead of relying on the model’s subjective judgment that it is “done.”
# Example: a task unit with acceptance conditionstask = {"goal": "Generate a quarterly operations analysis summary","steps": [{"id": "s1", "action": "collect", "accept": "records > 0"},{"id": "s2", "action": "aggregate", "accept": "schema_valid"},{"id": "s3", "action": "summarize", "accept": "length<=800"}],"budget": {"max_steps": 12, "max_tool_calls": 20}}
3. Tool Orchestration: Capability Boundaries and Least Privilege
Tools are the only channel through which an agent reaches the real world, and the main source of risk. Follow three principles when orchestrating them. First, clear semantics: a tool description must state its applicable scenarios, input constraints, and failure semantics; a vague description leads directly to wrong calls. Second, least privilege: separate write operations from read operations, and require explicit confirmation or secondary validation for high-risk actions. Third, idempotency and rollback: actions involving external systems should be designed so that repeated execution produces no extra side effects.
At the structural level, combine “routing + allowlist + retry policy”: routing decides the set of tools available to the current step, the allowlist restricts parameter values, and retries apply only to recoverable errors with an upper limit on total calls to keep the model from falling into a tool loop.
4. State Management: Making Processes Pausable and Recoverable
State is what distinguishes an agent from a single question-and-answer exchange. A usable state model contains at least four kinds of information: task context (goal and constraints), execution progress (completed steps and artifacts), intermediate memory (structured results and summaries), and control information (retry counts, budget consumption, termination reason).
The key design points are separating reads from writes and enforcing structure. State should be as structured as possible and carry a version number, avoiding unbounded growth of free text; use summary compression for long conversation history, keeping the basis for decisions while discarding redundant wording. Also make explicit which state can be persisted across sessions and which is valid only for the current run, so private data is not retained unintentionally.
5. Subgraph Mechanisms and Multi-Agent Collaboration
Describing a complex flow with a single graph quickly gets out of control. The value of subgraphs is layered encapsulation: turn reusable capabilities (such as retrieval, validation, and formatting) into independent subgraphs, with the main graph handling only orchestration and decisions. Subgraphs communicate through explicit data contracts with fixed input and output structures, which makes them easy to test and replace individually.
Multi-agent collaboration suits scenarios where responsibilities genuinely differ, for example a “planner-executor-reviewer” triangle: the planner decomposes the goal, the executor calls tools to produce results, and the reviewer judges whether rework is needed against the acceptance criteria. Collaboration must set a global termination condition and a maximum number of rounds; otherwise agents tend to pass responsibility around or polish endlessly. Keep the number of roles within what is necessary, since every added role brings context-passing cost and latency.
# Example: termination control for a review loopdef review_loop(state):for round in range(state.max_rounds):result = executor(state)verdict = reviewer(result, state.accept)if verdict.passed:return resultstate = update(state, verdict.feedback)return fallback(state)
6. Durable Execution and Fault Tolerance
Production environments must assume that “failure can happen at any time.” The core of durable execution is persisting the input, output, and state of every step so the flow can continue from the breakpoint after a process restart, network jitter, or human intervention. Three things matter in implementation: checkpoint granularity (save per step rather than per session), recovery consistency (avoid re-executing non-idempotent actions), and human takeover (high-risk nodes support pausing to wait for confirmation).
Timeouts and circuit breaking are also required: when a single step times out, the overall budget is exceeded, or consecutive failures reach a threshold, actively degrade to a fallback path and record the degradation as an auditable event.
7. Observability, Evaluation, and Continuous Optimization
Without measurement there is no optimization. Build three layers of observability: the call layer records the latency, token consumption, and error codes of each model and tool request; the flow layer records step transitions, rework counts, and termination reasons; the outcome layer uses a fixed evaluation set to measure task success rate, format compliance rate, and human correction rate. General capabilities such as the log service, monitoring and alerting, and object storage offered by Baidu AI Cloud can carry trace data, configure threshold alerts, and archive evaluation samples, feeding online issues back as regression cases.
The order of optimization should be: first fix the process and tool descriptions (lowest cost, highest return), then tune prompts and model selection, and only then consider adding roles or introducing more complex orchestration. Most outcome problems come from missing constraints, not insufficient model capability.
8. Deployment Checklist
- Does every step have a clear acceptance signal and a failure fallback?
- Do tools satisfy least privilege, idempotency, and rollback?
- Is state structured, versioned, and scoped for persistence?
- Do subgraphs have independent data contracts and test cases?
- Do multi-agent setups have global round and budget limits?
- Are breakpoint recovery and human takeover available?
- Is there a dashboard for the four metrics: success rate, rework rate, latency, and cost?
Following this path, agents can move from “able to demo” to “operable,” maintaining stable delivery quality in real, complex scenarios.
