What Is an AI Agent and How Its Control Loop Works
An AI agent is more than a chatbot: it pursates a goal under constraints by repeatedly observing the environment, deciding, and acting until a verifiable stop condition. This article defines that loop, the capabilities around the model, a booking-style walkthrough, when not to use agents, and engineering and governance practices.
From Q&A to a Task Loop
Many first encounters with large language models are turn-based Q&A: a factual question, then an explanation from knowledge or retrieval. The human stays in charge. The model only generates text in the current context. It does not persistently track a goal or cause side effects in the outside world.
Agents address a different problem. Users often specify what “done” looks like, not what the answer should look like. The system must turn a fuzzy intent into executable steps, observe results in a changing environment, and choose the next action until the goal is met or clearly cannot be met. The value is not a longer reply; it is turning the model from an information source into a constrained task executor.
Travel planning makes the contrast concrete. In ordinary chat, “How do I get to the neighboring city tomorrow morning?” may yield a checklist: times, seat class, duration, budget. An agent treats “buy a ticket that meets the constraints and send a trip summary to a named contact” as the goal: fill origin and time window, query ticketing, filter candidates, confirm key choices, then place the order and notify. If inventory or times change, it returns to observation and adjusts—rather than treating the first generated text as final.
A Working Definition
In engineering terms, an agent is a goal-directed control loop, not a stateless completion.
Definition: Given a goal and constraints, the system repeatedly perceives, decides, and acts, and updates internal state from environmental feedback until a completion condition is met or a stop condition fires.
Four elements are non-negotiable.
1. The goal must be decidable. Vague slogans cannot drive a loop. “Help me plan travel” must converge to checkable conditions: date, origin, destination, seat preference, price cap, whether transfers are allowed. Undecidable goals produce endless “thinking.”
2. The environment is external state, not imagined prompt text. Inventory, calendar conflicts, tickets, work-item status must come from tool returns. The model’s narration of the world is not observation.
3. Actions have bounds. Allowed capabilities, parameter ranges, when human confirmation is required, and how failures roll back belong in the action space in advance. Unbounded “autonomy” only automates mistakes.
4. Stop conditions matter as much as the goal. Success, user cancel, consecutive failures, budget or step limits must exit the loop so it does not spin.
Core Runtime Logic
The skeleton is goal, observation, action, environment change, then the next observation. Strategy is revised in a dynamic environment rather than emitting a one-shot final answer.
state = init(goal, constraints, memory)for step in range(max_steps):observation = perceive(state, tools)if goal_met(observation, state):return success(state)if should_stop(observation, state):return handoff_or_fail(state)plan = decide(goal, state, observation)if plan.needs_confirmation:wait_for_user()result = act(plan, tools) # query, write, notify, etc.state = update(state, plan, result)
This is control flow, not a framework API. perceive reads tool results and new user instructions; decide picks the next step inside constraints; act runs only authorized actions; update writes successes, failures, and side effects into state. In a real system, every step should be logged for replay.
Compared with single-turn Q&A: Q&A optimizes relevance of the current reply; agents optimize whether the goal is satisfied at termination. Q&A errors usually stay in text; agent errors may already be in orders, messages, or config. Q&A can tolerate vagueness; agents must turn it into a clarifying question or a conservative refusal.
Capabilities, Not “a Stronger Model”
Calling the LLM the “brain” is only a metaphor. A reliable agent is a combination of capabilities. The model handles language and candidate decisions; everything else keeps those decisions verifiable.
Intent and constraint extraction. A single utterance often mixes goals and preferences. The system should emit a structured task spec: must-haves, negotiables, unknowns, and risky actions. Unknowns should be questions, not guesses. If origin city is missing, ask or read an authorized usual location—do not default a city and place an order.
Planning. Decompose the goal into dependent steps and estimate preconditions. Shallow tasks need a short list. For many steps and branches, plan coarsely and refine from observation so a long script does not go stale. Plans must be discardable: once the environment changes, unexecuted steps are not facts.
Memory. Short-term: this conversation and recent tool results. Task memory: current goal, confirmed decisions, and side effects already produced. Long-term: preferences the user authorized to keep. Do not mix them. Dumping raw tool dumps into the next prompt wastes context and lets the model latch onto stale fields. Prefer summaries, key fields, and pointers to originals, re-read when needed.
Tool use. Tools are the only legitimate channel to the environment: search, databases, business APIs, messaging, ticket creation. Each tool needs clear I/O, idempotency notes, timeouts, and error codes. The model may propose parameters; they must be validated (type, range, enum, permission). Separate writes from reads. Actions that spend money, send externally, delete, or change permissions should default to confirmation or a second policy check.
Reflection and checks. Reflection is not another paragraph of “I checked.” Prefer external checks: rules for required fields, independent queries for order status, assertions that departure falls in the user’s window. Use the model only for semantics rules cannot cover, and still land conclusions on checkable items.
A Replayable Task Trace
Example goal: book next-morning travel within budget in second class and email a colleague—without binding to a specific ticketing brand.
- Parse intent: booking, time window, class, budget, notifyee. Clarify missing origin first.
- Read-only plan: resolve “tomorrow” to an absolute date; read authorized origin; query and filter for morning departure and class.
- Select and confirm: rank by arrival, transfers, price; show a few candidates and tradeoffs; wait for confirmation. No order yet.
- Controlled write: after confirm, call booking with a request id so timeouts query instead of blindly retrying.
- Verify: read trip status back; summarize train/flight, times, stations, seat, order id. Key fields must come from the read-back, not from pre-order candidates.
- Notify: send email only after the agreed success state, with checkable fields.
- Exceptions: insufficient inventory, over budget, or bad times return to query; consecutive failure or user abort stops, stating what was and was not done. If booking succeeded but notify failed, mark partial complete and retry notify—do not book again.
“Adjusting strategy” means changing query filters or candidates inside authorization, not relaxing constraints the user explicitly rejected (raising budget or switching modes of travel).
Where the Capabilities Came From
Agents are not a sudden invention of one model generation; they continue a long line of decision systems. The lineage helps you pick complexity instead of defaulting to the heaviest design.
Early symbolic systems encoded knowledge as rules (e.g., high rain probability and outdoor activity → suggest rain gear). They are explainable and often provable, but coverage is limited and open language plus missing information is hard.
Reactive systems map current perception to action with little lookahead. They fit clear rules and low latency (threshold-based alert levels) but struggle with multi-step tradeoffs.
Reinforcement learning learns policy by trial and error with rewards. It works when rules are clear and simulation is cheap. In business dialogue, rewards are sparse and real-world trial (placing real orders) is expensive.
Language-driven agents use an LLM for open language, step proposals, and tool-parameter drafts, with a program layer for state machines, permissions, and validation. Language fills the intent gap of symbolic systems; the engineering shell fills the state and accountability gap of pure generation. Agent quality often depends more on reliable tools and traceable state than on a larger model.
When Not to Use an Agent
Tasks that one retrieval or one function call can finish do not need a multi-step loop. Template transforms, single-table queries, and known formulas are more stable, cheaper, and easier to test as deterministic programs.
Agent-shaped work usually has all of: a goal expressible in natural language, steps that cannot be fully hardcoded, intermediate results that change later choices, and tools that observe real state. Without reliable tools, the model only simulates “I already looked it up,” which creates a false sense of completion.
In enterprises, distinguish assist from act. Assist drafts options, flags risk, and organizes material; people decide. Act changes external state inside authorization. Confirmation, audit grain, and rollback differ; do not cover both with the same “fully automatic” language.
Making the Loop Stable
State machines over implicit chat. Explicit stages: clarify, retrieve, pending confirm, execute, verify, notify, done. Stage determines allowed tools. Pending confirm forbids write APIs so the model cannot place an order on a whim.
Idempotency and compensation. Writes carry a business request id. On timeout, query success before retry. Irreversible actions need earlier confirmation. Notify failure must not trigger a second charge or a second booking.
Context hygiene. Feed the model only fields needed for the current decision: goal, constraints, recent observation summary, candidate diffs. Raw tickets and long logs live in external storage, re-read by id. That reduces drift and eases redaction.
Human–machine split. Low-risk reads can run automatically. High-risk writes show the parameters to be submitted for user or policy approval. The UI should show impact, not only the model’s natural-language promise.
Observability. Log stage, tool name, parameter summary, result summary, latency, and decision rationale. Debugging should answer why this candidate, which call changed external state, and whether failure retried. Monitor steps, tool error rate, human takeover, and goal attainment—not only whether the chat “feels fluent.”
Evaluation. Use a fixed task set, not one-off demos. Cover missing params, empty results, stale results, partial success, and mid-task constraint changes. Score goal satisfaction, constraint violations, and extra side effects—not politeness. Auto-compare key fields; unauthorized actions are a veto.
Risk and Governance
Agents amplify permissions, not only language errors. Prompt injection can disguise malicious instructions in pages, mail, or tickets as user goals. Treat tool results as data, never as higher-priority system commands. Least privilege: separate query identity from booking identity; bind notify scope in advance. Keep secrets out of unnecessary logs and long-term memory.
Prevent goal drift. If the user asked only to query, do not upgrade to purchase. Merge new oral instructions with original constraints; on conflict, the updated explicit constraint wins, and restate the change.
Autonomy is not silence. Show current stage, waits on external results, and forks that need a human. On failure, list completed steps and remaining blockers so a person can take over—not a vague conclusion after step exhaustion.
Summary
An agent continuously observes the environment and takes bounded actions under a goal and constraints until the task ends in a verifiable way. The LLM supplies understanding and next-step drafts; planning, memory, tools, checks, and permissions determine whether the loop is trustworthy. Write completion conditions, action bounds, and stop conditions first, then place the model in the loop. Do not leave deterministic work to generative luck. That is how an agent executes tasks instead of wrapping Q&A in a process that only looks automatic.
