AI Agent Development: Core Logic and Practical Patterns
This article explains how to build production-grade AI agents using graph-based orchestration. It maps orchestration concepts to programming language fundamentals, then covers state design, nodes and edges, cyclic routing, parallel fan-out and aggregation, checkpointing and recovery, human-in-the-loop interrupts, observability, evaluation, cost control, and common anti-patterns. The goal is to turn unpredictable agent demos into testable, recoverable, and collaborative systems.
1. Why Agents Need a New Orchestration Approach
Early AI applications were mostly a straight line: receive input, assemble a prompt, call the model, return the result. That kind of chain is enough for a demo, but problems surface quickly in real business scenarios. Tasks require multi-step reasoning, external tool calls, retries on failure, human confirmation at critical points, and the ability to continue after a process restart. Linear calls cannot express these semantics, so developers end up forcing the flow into scripts with large amounts of conditional logic, producing a hard-to-maintain “prompt mudball.”
The industry has gradually converged on a clearer abstraction: treat the agent workflow as a stateful graph. Each computation step in the graph only cares about reading and updating shared state, while the order and branching between steps are declared by edges. This paradigm separates “what to do” from “when to do it,” making complex logic describable, testable, and observable. Note that this is a general engineering paradigm; different technical solutions expose different API shapes, but the underlying elements are highly consistent.
2. Migrating the Programming Language Mental Model to Agent Orchestration
The fastest way to understand graph-based orchestration is to align it with the core elements of a programming language. Any language needs data, functions, control structures, and storage; graph-based orchestration provides functionally equivalent abstractions.
| Language Element | Orchestration Equivalent | Responsibility |
|---|---|---|
| Data | State | The information carrier that is read, merged, and passed along during the flow |
| Function | Node | The smallest computation unit that operates on state |
| Control flow | Edge | Determines execution order; supports static paths and conditional branches |
| Storage | Checkpoint | Persists state to support pause, resume, and replay |
| Exceptions and debugging | Interrupt | Suspends the flow at key points and hands the decision to a human or an external system |
The value of this mapping is that it pulls “agent development” back from mysticism into engineering: state is like an in-memory data structure, nodes are like pure or side-effect-controlled processing units, edges are like control statements, and checkpoints are like transaction logs. Teams can directly reuse existing experience with code review, unit testing, and troubleshooting.
3. State Design: The First-Order Problem That Sets the System Ceiling
State is the part of the design that needs the most care, because it determines the visibility scope of information and the merge semantics. Three principles are recommended in practice.
First, minimal and sufficient. Only include fields that genuinely need to be shared across nodes, such as the user’s original question, retrieved evidence snippets, tool call results, the current attempt count, and the final draft. Put intermediate debugging information into a separate observability channel instead of stuffing it into the main state; otherwise the state balloons quickly and merge logic becomes unpredictable.
Second, define an explicit merge strategy. Parallel nodes write back to state at the same time, and without an agreed merge rule, later writes overwrite earlier ones. A common approach is to declare “append” semantics for list fields and “overwrite” semantics for scalar fields, and to fix this at the type level.
Third, keep it serializable. State must be persisted to disk to recover after a failure, so avoid storing objects that cannot be serialized, such as long-lived connections or file handles. Put large content in object storage and keep only a reference identifier in the state.
from typing import TypedDict, Annotatedimport operatorclass AgentState(TypedDict):question: strevidence: Annotated[list[str], operator.add] # Append-merge results from parallel nodesattempts: int # Scalar field, last write winsdraft: strartifact_ref: str | None # Store only a reference for large objects
4. Nodes and Edges: Making Control Flow Explicitly Visible
Nodes should have a single responsibility. One node does one thing: call the model to generate a plan, run one retrieval, call one tool, validate the output format, or perform a content safety review. The finer the nodes, the easier it is to locate failures and the easier it is to swap out an implementation on its own.
Edges come in two types. Static edges express a fixed order, while conditional edges express dynamic routing based on state. What complex business scenarios usually need is a “conditional edge with a loop”: when the review node finds that the draft lacks citations, it routes back to the retrieval node to gather more evidence and increments the attempt count; when the count exceeds a threshold, it routes to a fallback node that emits a degraded result. This cyclic structure is the key advantage of directed-graph orchestration over linear chains.
def route_after_review(state: AgentState) -> str:if state["attempts"] >= 3:return "fallback"return "retrieve" if not state["evidence"] else "finalize"
It is worth stressing that a loop must have an explicit convergence condition, otherwise you get infinite loops and runaway costs. In engineering, teams typically set three guardrails at once: a maximum attempt count, a timeout, and a budget cap.
5. Engineering Details of Parallelism, Fan-Out, and Aggregation
When a task can be split into mutually independent subproblems, fan-out parallelism can significantly reduce latency. But parallelism introduces two problems that must be handled: state merge conflicts and exception propagation. A recommended practice is to have each parallel branch write to its own field or list element, and have the aggregation node perform deduplication, sorting, and conflict resolution in one place. When any branch fails, the aggregation node decides whether the whole run fails or partial results are allowed to continue.
6. Persistence and Recovery: The Key Divide Between a Demo and Production
The checkpoint mechanism writes a state snapshot to external storage after each node executes, providing three capabilities: resuming from the latest snapshot after a process crash; continuing a long flow across requests and sessions; and supporting time-travel debugging, branching and replaying from any historical node. In practice, you need to balance snapshot write frequency against data volume, typically writing at node granularity and externalizing large fields by reference. The storage layer can use general-purpose capabilities, such as object storage for snapshots and artifacts, a message queue for asynchronous tasks, and logging plus monitoring and alerting services to observe the execution trace.
7. Human in the Loop: Embedding Review in the Flow Rather Than Bolting It On
High-risk actions should not be decided by the model alone. With an interrupt primitive, the flow can suspend before performing a write operation, publishing content, or initiating a transaction, submit the current state and the pending action to a human reviewer, and resume from the breakpoint once a decision arrives. Compared with “execute first, roll back later,” this upfront suspension is more controllable in both compliance and cost. The implementation key is that the interrupt point must be idempotent, and resumption must carry an explicit review decision to avoid repeating side effects.
8. Observability, Evaluation, and Cost Control
Agent systems are harder to debug than ordinary services because their behavior is non-deterministic. It is recommended to assign a trace identifier to each execution and record a summary of node inputs, a summary of outputs, latency, and token consumption; build a fixed set of test cases for regression evaluation, focusing on task success rate, rework count, and average number of steps; and at the budget level, set per-task step and call limits, routing to a fallback path when exceeded.
9. Common Anti-Patterns
One is cramming all logic into a single giant prompt, which makes it impossible to locate the cause of a failure. A second is uncontrolled state growth, where serialization and merge costs spiral. A third is loops without a convergence condition. A fourth is silently swallowed exceptions, where the flow appears to succeed but the result is missing. A fifth is placing the review step after the side effect has already occurred.
10. Conclusion
The essence of graph-based orchestration is using engineered structural constraints to tame the uncertainty of models. Design the five elements—state, nodes, edges, checkpoints, and interrupts—clearly, and an agent goes from a demo that is hard to reproduce to a production system that is testable, recoverable, and collaborative. In general engineering practice on cloud platforms such as Baidu AI Cloud, combined with foundational capabilities like object storage, container platforms, and monitoring and alerting, teams can focus their energy on business semantics and evaluation systems instead of repeatedly building infrastructure.
