Skip to content
An agent is a closed-loop control system

An agent is a closed-loop control system, not a single call

My earliest version of an Agent had just a single while loop in the code. It looked great when running the demo: I asked it to “check tomorrow’s weather in Shanghai, and also see if meeting room 3 is free,” and it called two tools and produced a coherent conclusion. On the third day after launch, something went wrong: a certain query API returned 200 with an empty array, and the model interpreted “can’t find it” as “no restrictions,” then went on to perform a series of actions it shouldn’t have. There wasn’t a single line of exception in the logs; the chain was working.

After that, I stopped evaluating Agents by “it runs.” A single LLM call is approximately a pure function; an Agent is a stateful closed-loop control system. What a control system should care about isn’t whether the output at some step is correct, but whether errors get amplified by feedback. This perspective is the starting point for the next fourteen articles.

Article 1/15 of this series · Next: Planner: Task Decomposition and Verifiable Plans

The difference between one call and one loop is state

A single LLM request can be abstracted as text_out = f(prompt, weights): given the same input, the output distribution is basically consistent, with no side effects. Failures manifest as timeouts, rate limits, or format errors; these are easy to diagnose because they have clear signals.

What an Agent adds is the environment. Each step produces an action, the action changes the external environment or internal state, the environment feeds the result back to the model as a new observation, and the model then decides the next action. Written as a recurrence, it’s just three lines: the environment turns the result of the previous action into a new observation, o_t = E(s_{t-1}, a_{t-1}); context construction determines what the model sees this round, h_t = C(h_{t-1}, a_{t-1}, o_t); the model produces the next action based on this context, a_t = M(h_t).

Here E is the environment (tools, databases, file systems, external APIs), M is the model, C is the context construction strategy, h is the segment of context fed into the model, and s is the real-world state. The most easily overlooked of the three symbols is C: most cases of “the Agent got dumber” are not model degradation, but h being badly constructed—history truncated, observations compressed too aggressively, error messages mixed together with normal results.

The corollary is very practical: state s and context h are not the same thing. h is merely a lossy projection of s, and it must be re-projected every loop iteration. Blindly concatenating all historical messages into the prompt looks like “all the state is there,” but in reality it has neither structure nor queryability, and in long tasks key fields get squeezed out by the window. My approach is to externalize state as structured records and project context according to the needs of the current step; I’ll expand on this when discussing memory in Article 13.

The skeleton of the ReAct loop: control must stay in the code’s hands

ReAct is often described as a prompting technique, but in engineering it’s actually a loop skeleton: the model outputs Thought / Action, the code parses and executes the Action, then feeds the execution result back as an Observation. The key is that control over the loop, termination, retries, and timeouts all stays on the code side; the model is only responsible for giving the next action. Letting the model decide “should I stop” is equivalent to handing the termination condition to a probabilistic output.

PYTHON18 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def run_agent(task, max_steps=12, timeout_s=120):
state = State(task_id=new_id(), plan=None, effects=[], observations=[])
deadline = time.monotonic() + timeout_s
for step in range(max_steps):
if time.monotonic() > deadline:
return halt(state, reason="timeout")
ctx = build_context(state) # 投影,不是全量历史
action = model.decide(ctx, tools=TOOL_SCHEMA)
action = validate(action) # 类型、范围、权限
if action.type == "final":
return halt(state, reason="final", answer=action.answer)
if is_repeated(state.recent_actions, action):
inject_hint(state, "上一步动作重复,换一种策略")
continue
obs = execute(action, idempotency_key=make_key(state, action))
state.observations.append(compact(obs)) # 观测也要限长
trace.write(step, action, obs)
return halt(state, reason="step_limit")

There are a few details in this skeleton that I think can’t be skipped. validate is placed before action execution, not as after-the-fact validation after the model finishes outputting; is_repeated should compare normalized parameters, otherwise calls with timestamps or random IDs look different every time while actually spinning in place on the same action; compact truncates or summarizes observations—when a database query returns tens of thousands of rows, feeding them back verbatim instantly eats up the window.

The loop itself can be drawn as below; exit conditions must be determined by code:

stateDiagram-v2
  [*] --> 构造上下文
  构造上下文 --> 模型决策
  模型决策 --> 动作校验
  动作校验 --> 执行动作: 通过
  动作校验 --> 停止: 不合法或重试超限
  执行动作 --> 观测压缩
  观测压缩 --> 构造上下文: 未满足完成条件
  观测压缩 --> 停止: 给出 final
  构造上下文 --> 停止: 超时或步数上限
  停止 --> [*]

I generally explicitly list four types of termination conditions: the model gives final, step limit, total timeout, external interruption (user cancellation, budget exhaustion). There’s also a hidden one: if N consecutive steps produce no new valid information, it should stop early. The step limit is not a fallback decoration; it’s a cost upper bound. Without it, a hallucination of “one more query will find it” can burn hundreds of thousands of tokens.

State machine perspective: turning “going off track” into detectable events

Write the Agent as a four-tuple (S, A, T, H): S states, A action set, T transition function, H halting predicate. The benefit of writing it this way is that many vague questions become checkable constraints. “Is the task done” becomes “are all required_fields in S non-empty and passing validation”; “can this action be executed” becomes “does the current phase allow this action type.”

The state I store looks roughly like this:

JSON10 lines
1
2
3
4
5
6
7
8
9
10
{
"task_id": "t_8f31",
"phase": "collecting",
"plan_version": 3,
"cursor": 4,
"required_fields": {"date": null, "room_id": null, "approval": null},
"effect_ledger": [{"key": "t_8f31/s3/notify", "status": "committed"}],
"budget": {"tokens_used": 18400, "tokens_left": 11600},
"replan_count": 1
}

The value of fields like required_fields is that it turns “completion conditions” from natural-language judgment into boolean expressions in code. The model fills in values; the code makes the determination. In Article 2 I’ll extend this into a verifiable plan.

Looking back at the incident from the beginning: the API returning an empty array is a legitimate observation, but the transition function mapped it to the wrong next state. The problem wasn’t in M; it was that T lacked a guard for “empty results require explicit confirmation.” The fix isn’t to change the prompt, but to wrap [] at the tool layer into an observation object with semantics, such as {"status": "empty", "meaning": "查询无匹配,不代表无限制", "raw": []}. The semantics of observations must be defined by the engineering side; you can’t expect the model to guess them.

How errors get amplified by feedback

The most dangerous property of a closed-loop system is positive feedback. A slight misjudgment at step t gets written into the environment through an action, and by step t+1 the observation is already “contaminated fact”; the model continues reasoning on this false premise. The further it goes, the more self-consistent the logs look, and the harder it is to find that the starting point was wrong.

The most common error amplification is semantic misreading: reading [], null, 0, 404 as “no constraint,” and the model continues doing completely reasonable reasoning on an empty premise. Even more troublesome are irreversible side effects—the email has been sent, the database has been written, the order has been placed—only to discover that the earlier understanding was wrong, and the rollback cost is far higher than recomputation. There’s also context drift: in long tasks, early constraints get pushed out of the window by large blocks of later observations, and the model starts violating the rules it set in step 2 without being aware of it.

The corresponding guardrails fall into three layers, and all must be moved forward to before action execution:

Layer What is checked Means
Output layer The action given by the model Strict JSON Schema validation, enum constraints, parameter ranges
Semantic layer Whether the action is consistent with the current state Completion conditions, dependency checks, reconciliation with the user’s original constraints
Execution layer The action’s impact on the external world Idempotency keys, side-effect ledger, manual confirmation for dangerous actions

The third layer is the only one that prevents “irreversibly wrong.” Actions like classification, summarization, and draft generation cost at most some tokens to recompute; replaying a notification, payment, or state change once is an incident. Before acting, I make a habit of listing a side-effect table, marking each action as recomputable, overwritable, once-only, or irreversible, and then deciding where to place the checkpoints.

Trade-offs of three control granularities

For the same task, control granularity can vary widely. Choosing the wrong granularity costs far more than choosing the wrong model.

Single-loop ReAct has the model look at the latest observation before deciding each step, which is most stable when the environment changes fast and the path is uncertain. The cost is one model call per step, so latency and tokens grow linearly with step count; and with no global view, it tends to probe repeatedly in local loops. It suits exploratory tasks, such as diagnosing an unknown fault or locating a problem in an unfamiliar codebase.

Plan-and-Execute generates a structured plan once up front, the execution layer runs according to the plan, and the model only intervenes on replanning. It saves tokens, parallelizes, and is predictable, but once the plan is wrong, it’s hard to turn back midway. It suits tasks with clear steps and dependencies, such as generating reports from a fixed template or batch-processing structured data.

Layered control separates the planner, executor, and reviewer, with the reviewer only judging “does this step’s result satisfy the completion condition.” One extra model call buys recoverability: on execution failure you can retry locally instead of rerunning everything. It’s only worth it for long tasks and multi-agent collaboration (Part 14).

Dimension Single-loop ReAct Plan-and-Execute Layered control
Per-step latency High Low Medium
Total tokens Linear with steps Relatively low Relatively high
Mid-course correction Native Requires explicit replanning Local support
Parallelism Weak Strong Medium
Main risk Spinning in place One-shot plan error Cross-layer state inconsistency

My current default: single-loop for short tasks (estimated within 5 steps), plan-then-execute for long tasks, and add a review layer only when irreversible changes are involved. Don’t start with layering—most “complexity” is actually poorly designed tools, not an insufficiently fancy control structure.

Boundaries of this lens

Treating an Agent as a control system pays off in observability, boundedness, and recoverability: every step has an explicit action, observation, and state snapshot, and when something goes wrong you can pinpoint the specific transition. The cost is more boilerplate, plus maintaining a structured state parallel to the prompt—when the two disagree, it hurts. As for one-shot Q&A and pure generation tasks, this machinery is pure overhead: no environment feedback means no closed loop to speak of.

There’s another case where I deliberately don’t close the loop: read-only analysis tasks. Having the model read the material once and give a conclusion is cheaper and less error-prone than having it look things up while thinking. The criterion is simple: will this step’s action change the environment? If not, don’t add a loop.

This piece only takes apart the “loop” itself. Who decides “what to do next” inside the loop, and how it’s validated, is the next piece’s job. Your current Agent—if I swapped all its tools for stubs returning empty results, would it stop, or keep confidently marching on?

Series index

  1. Agent Is a Closed-Loop Control System (this piece)
  2. Planner: Task Decomposition and Verifiable Plans
  3. Tool-Calling Protocol: From Schema to Idempotency
  4. Taking Apart a RAG Pipeline
  5. Chunking Isn’t Cutting Characters, It’s Cutting Semantic Boundaries
  6. Embedding Selection: Don’t Just Look at Leaderboard Scores
  7. Four Axes for Vector Database Selection
  8. Hybrid Retrieval: Sparse, Dense, and Score Fusion
  9. Reranking: Gains and Costs of the Two-Stage Architecture
  10. Context Construction: Recall Is Just the Beginning
  11. RAG Evaluation: No Test Set, No Optimization
  12. Agentic RAG: Handing Retrieval to an Agent Scheduler
  13. Reading, Writing, and Forgetting in Agent Memory Systems
  14. Multi-Agent Collaboration: Topology, Communication, and Termination
  15. After Launch: Observability, Cost, and Guardrails

About this Post

This post is written by Lu's Blog, licensed under CC BY-NC 4.0.

#Agent #Architecture #ReAct

Comments