From Prompts to Loops: A Practical Guide to Agent Automation Engineering
This article explains the shift from hand-written agent prompts to state-driven loops, a pattern now favored by engineers behind open-source agent frameworks and AI coding tools. It defines the five core elements of an agent loop, contrasts loops with scheduled cron-style tasks, and lays out six engineering requirements for reliable deployment: externalized state, termination conditions designed up front, evaluators separated from executors, small reversible steps, observability, and permission sandboxing. It also covers common anti-patterns and how loop infrastructure maps onto general cloud service categories. The key takeaway: prompt engineering improves single-response quality, while loop engineering delivers stability, convergence, and cost control for long-running tasks.
1. One Slogan, One Paradigm Shift
Two senior engineering leaders recently made the same observation within days of each other: one leads an open-source agent framework, the other an AI coding tool. Neither writes prompts line by line for their agents anymore. Instead, they design a loop and let the loop drive the agent.
This is easy to misread as “prompts no longer matter.” A more accurate reading: prompts have changed from instructions that humans write for an agent into inputs that the system generates and feeds to the agent according to rules. The center of human work has moved up a level, from content creation to process design.
Three stages make the difference clear:
- Manual stage: a human writes one instruction, the agent executes it once, the human checks the result, then writes the next instruction.
- Orchestration stage: a human chains several steps into a pipeline, but every step still depends on a prompt written in advance.
- Loop stage: a human defines only the goal, constraints, and termination conditions; the loop handles scheduling, observation, error correction, and rescheduling.
2. What a Loop Actually Is
A loop is not “sending the same sentence over and over.” It is a stateful closed-loop control system with at least five elements:
- Goal and acceptance criteria: a decidable completion condition, not a vague “make it a bit better.”
- State carrier: the task list, current progress, approaches already tried, and reasons for failure, usually persisted in files or data structures.
- Scheduler: decides what the next round does, what input it receives, and who executes it.
- Executor: the layer that actually calls the model or the tools.
- Evaluation and termination: decides whether to continue, roll back, or stop.
Illustrative pseudocode:
state = load_state(goal)while not state.done and state.round < MAX_ROUNDS:prompt = render(state) # prompt generated from stateresult = agent.run(prompt, tools) # execution and tool callsstate = update(state, result) # structured persistenceif evaluator.reject(state):state = rollback(state) # roll back to the last stable point
The critical parts are render and update: the prompt is no longer a constant but a function of state, and the execution result is no longer a natural-language running log but structured data that a program can parse.
3. How Loops Differ from Scheduled Tasks
Many platforms already support periodically triggered jobs, which raises the question: isn’t a loop just a scheduled task with a while statement? The two differ on four dimensions.
- Trigger basis: a scheduled task is clock-driven with a fixed period; a loop is state-driven and advances only when conditions are met.
- Memory: each run of a scheduled task is independent; a loop must persist context and accumulate it across rounds.
- Failure handling: a failed scheduled task is usually retried or raises an alert; a loop needs diagnosis, rollback, and alternative paths.
- Termination semantics: a scheduled task never ends on its own; a loop must converge explicitly, otherwise it becomes runaway consumption.
In one sentence: scheduled tasks answer “when to run,” while loops answer “what to run and when it is done.”
4. Six Engineering Requirements for Production
4.1 Externalize State and Make It Recoverable
Context cannot live only inside the model’s session. Sessions get truncated, compressed, and wiped on restart. The reliable approach is to write task state to structured files or records and rebuild context from disk at the start of every round. If the process crashes, execution resumes from the last stable point.
4.2 Design Termination Conditions First
Decide how to stop before deciding how to run. Common termination conditions include: all acceptance tests pass, two consecutive rounds produce no new useful information, a round or time limit is reached, or the cost per task exceeds a threshold. A loop without termination conditions is essentially a billing loop that never ends.
4.3 Keep the Evaluator Independent from the Executor
Having the same model do the work and grade itself invites self-approval. A safer design introduces independent evaluation: run tests, static checks, rule validation, or bring in an evaluator role with a clean context. The evaluator’s output must be a decidable verdict, not a subjective description.
4.4 Take Small Steps and Keep Them Reversible
Each round should advance one verifiable small goal and keep a snapshot. When the direction turns out to be wrong, roll back to a stable point instead of patching on top of an ever-growing context of errors.
4.5 Observability
At minimum, record: a summary of each round’s input, tool calls and their latency, token and cost consumption, evaluation verdicts, and the state transition path. Observability determines whether you can find out why the agent is going in circles.
4.6 Permissions and Sandbox Boundaries
The higher the level of automation, the higher the cost of a mistaken action. Run in an isolated environment, apply allowlists and quotas to write operations, delete operations, and external access, and keep a human confirmation step for critical actions.
5. Common Anti-Patterns
- Stateless loops: every round starts from zero and repeats the same work.
- Endless self-correction: no evaluation criteria, so the model keeps “optimizing a bit more.”
- Context bloat: stuffing the entire history into the prompt quickly hits the context window limit and dilutes attention.
- Undecidable goals: acceptance criteria such as “more elegant” make convergence impossible.
- Missing budget guardrails: no round or cost caps, so the bill runs out of control.
6. Pairing Loops with General Cloud Capabilities
The infrastructure requirements of loop engineering map onto general cloud product categories. State and snapshots fit object storage or file storage; decoupling between rounds and smoothing out bursts can use a message queue; the execution environment can use a container platform for isolation and elastic scaling; full-chain records go to a logging service; anomalies and overspending reach the on-call person through monitoring and alerting; keys and configuration are managed by a unified configuration and credential management mechanism. Baidu AI Cloud offers corresponding capabilities in these general categories, and you can select and combine them according to your own architecture. The core principle is to separate the state, execution, and observability layers.
7. Conclusion
“No longer writing prompts, but designing loops” essentially turns the agent from a tool into a managed runtime. Prompt engineering improves the quality of a single output; loop engineering delivers stability, convergence, and cost control for long-running tasks. Whether a loop is sound comes down to three questions: can it recover, can it converge, and can it be audited.
