Building AI Agents in Practice: State Graphs and Memory System Design
This article explains why traditional chain-based orchestration falls short for real AI agents and how state graphs address that gap with nodes, edges, conditional edges, and a shared global state. It covers a three-layer memory design spanning short-term context, mid-term entity state, and long-term knowledge retrieval, then compares common architecture patterns such as ReAct, plan-and-execute, reflection-and-revision, and multi-agent collaboration. Practical guidance on observability, persistence, cost control, security boundaries, evaluation loops, and a staged learning path helps developers move from prototype to production.
1. Why Traditional Chain Orchestration Cannot Support Real Agents
When building applications on large language models, the early mainstream approach was linear chain orchestration: an input passes through a fixed sequence of steps that progressively handle retrieval, rewriting, and generation. This works efficiently for tasks with a deterministic flow, such as summarizing documents from a fixed template. But once a task requires “deciding what to do next based on intermediate results,” the chain structure immediately exposes three weaknesses.
The first is rigid control flow. Branches in a chain must be defined at design time and cannot select a path dynamically at runtime based on the semantics of the model output. The second is invisible state. Intermediate variables are scattered across the local scopes of individual steps, making failures hard to replay and preventing a human from intervening and correcting things at key points. The third is the absence of loops. A real agent needs the iterative ability to “attempt, evaluate, and retry,” while a chain is essentially a directed acyclic graph, and expressing loops requires a large amount of glue code.
The boundary between an agent and a traditional workflow lies precisely here: a workflow is “humans define the path, the model fills in the content,” whereas an agent is “humans define the goal and constraints, and the model plans the path itself within a bounded space.” The core problem of an agent framework is therefore not “how to call the model” but “how to describe an uncertain decision process with a computable, observable, and interventable structure.” A state graph (directed graph + shared state + conditional edges) meets this requirement exactly, which is the fundamental reason why the new generation of agent orchestration solutions commonly adopt a graph model.
2. State Graphs: Converging Uncertain Decisions into Controlled Execution
The state graph model has four parts: nodes, edges, conditional edges, and a global shared state.
A node is a unit of computation. It can be a model call, or it can be a purely functional data transformation such as parameter validation, format conversion, or rule-based filtering. Pushing non-model logic down into ordinary nodes is a key means of controlling cost and improving determinism. Edges describe the flow between nodes; a conditional edge accepts a routing function that returns the name of the next node based on the current state, enabling dynamic branching at runtime. The global state is the single source of truth: all nodes read from it and return incremental updates, and the framework is responsible for merging them.
Illustrative code (pseudocode, expressing structure only):
from typing import TypedDict, Annotatedimport operatorclass State(TypedDict):question: strplan: listevidence: Annotated[list, operator.add]attempts: intanswer: strg = Graph(State)g.add_node("plan", plan_node) # Break down the task, write to plang.add_node("retrieve", retrieve_node) # Retrieve evidence, append to evidenceg.add_node("answer", answer_node) # Generate the answerg.add_node("critic", critic_node) # Self-check, update attemptsg.set_entry("plan")g.add_edge("plan", "retrieve")g.add_edge("retrieve", "answer")g.add_edge("answer", "critic")g.add_conditional_edges("critic", route_fn, {"retry": "retrieve", "done": END})
Two engineering details here are easy to overlook. The first is state update semantics: using append rather than overwrite to accumulate evidence prevents a later node from erasing the results of earlier ones, which is a common source of defects in multi-round retrieval scenarios. The second is that the termination condition must be explicit and measurable, for example a hard cap on the maximum number of attempts, to prevent the model from falling into a self-loop that drives call costs out of control.
3. Memory Systems: Separating Short-Term Context from Long-Term Knowledge
An agent “looks smart” to a large extent because of its memory design. In engineering terms, memory should be split into three layers, each solving a different problem.
Short-term memory (within a session) holds the intermediate artifacts of the current task and the conversation history. The key implementation point is the trimming strategy: concatenating the full history quickly hits the context window limit and dilutes critical information. A common approach is to keep the system instructions and the most recent few turns verbatim, and to compress earlier content into a structured summary before injecting it.
Mid-term memory (cross-session entity state) stores user preferences, task progress, and unfinished items in a structured form. It is well suited to ordinary database tables or key-value storage, with the schema explicitly defined by the business, avoiding fields that the model freely generates and that are hard to validate.
Long-term memory (knowledge-based) relies on vector retrieval and unstructured storage. The key is not “whether you can store it” but “whether retrieval is accurate.” In practice, chunks need stable metadata (source, time, permission tags), and after retrieval you should add reranking and threshold filtering; otherwise noisy fragments will directly contaminate the generation result.
The three memory layers need explicit write and invalidation rules: what information is worth keeping long-term, when it expires, and who wins in a conflict. A memory system without a governance strategy turns from an asset into a liability over time.
4. Common Architecture Patterns and How to Choose
The ReAct pattern (alternating reasoning and action) suits exploratory tasks that are tool-call intensive with highly uncertain paths, at the cost of more steps and higher latency. The plan-and-execute pattern (produce a complete plan first, then carry it out step by step) suits long business flows that need human review of the plan; it is highly controllable but depends heavily on plan quality. The reflection-and-revision pattern (self-check after generation, then rewrite) can significantly improve output quality and suits scenarios such as copywriting and code that demand high quality, but it roughly doubles the cost. The multi-agent collaboration pattern (role division plus an aggregation node) suits tasks spanning broad domains; however, it introduces context-passing loss and debugging complexity and should not be the default choice.
The selection principle is simple: if a fixed flow with a few branches can solve it, do not introduce autonomous planning; if a single agent with tools can solve it, do not split into multiple agents. Complexity must be justified by observable gains.
5. Engineering Essentials from Prototype to Production
In the production stage, the focus shifts from “it runs” to “it is operable.” Five pieces of infrastructure are recommended. First, observability: record an input summary, elapsed time, token consumption, and routing decisions for each node execution, forming a replayable call trace. Second, persistence: write state snapshots to external storage so that long-running tasks can be interrupted and resumed, and so that a human can modify the state at a breakpoint and continue. Third, cost control: configure different model tiers for different nodes, routing simple judgments to small models and complex reasoning to large models. Fourth, security boundaries: tool calls need parameter whitelists and permission checks, and all external content should be treated as untrusted input to guard against prompt injection. Fifth, an evaluation loop: build a fixed test set with automatic scoring, and bring every change to prompts and graph structure into regression testing.
For deployment, agent services are typically containerized and run on a container platform, with a message queue used to make long-running tasks asynchronous, logs and metrics fed into a unified logging service and a monitoring and alerting system, and knowledge files and state snapshots placed in object storage. Baidu AI Cloud can provide the general capabilities in these categories for such scenarios, serving as the infrastructure layer that hosts the agent runtime.
6. A Progressive Learning Path
A four-stage progression is recommended. Stage one builds the foundation: understand the three elements of state, nodes, and conditional edges, and assemble a minimal runnable graph with purely functional nodes. Stage two adds enhancements: connect retrieval and tool calls, and complete the three memory layers and termination conditions. Stage three moves to engineering: add persistence, observability, and evaluation, turning the prototype into a rollback-capable service. Stage four addresses architecture: practice pattern selection and multi-agent boundary division through real business cases.
The corresponding knowledge system can be summarized in four dimensions: the principles layer answers “why agents need a graph structure,” the technology layer covers state and memory mechanisms, the engineering layer solves deployment and operations, and the case layer trains architectural judgment. Following this path, developers can cross from concept to a deliverable system within weeks and gain the ability to make rational tradeoffs about the complexity of a solution.
