The RL Problem and the Agent-Environment Loop
Imagine teaching a robot to walk, a program to play chess, or a thermostat to save energy. You never tell it the "correct" move at each instant. Instead you let it try things, watch what happens, and nudge it toward outcomes it likes. This is the essence of reinforcement learning (RL): learning through interaction rather than through labeled examples. The central abstraction that makes this precise is the agent-environment loop. It is a simple but rigorous cycle in which an agent observes a situation, acts, and receives feedback, over and over. This loop matters because it captures an enormous range of real problems. A recommendation system decides what to show a user. A data center decides how to cool its servers. A self-driving car decides when to brake. A game-playing program decides which move to make. In every one of these cases there is no static dataset of "correct answers." There is only a stream of experience, generated by the agent's own choices. There is also a scalar signal telling it roughly how well it is doing. Understanding the loop precisely is the first step toward everything else in RL. Value functions, policies, exploration strategies, and learning algorithms all live inside this cycle. The big picture is this: reinforcement learning formalizes sequential decision-making under uncertainty. It does so as an interaction between two entities, the agent and the environment. This interaction is mediated by three signals — state, action, and reward. The agent's job is to choose actions that maximize the total reward it accumulates over time. This means more than just the immediate reward. This requires reasoning about the future consequences of present choices. That is what distinguishes RL from simpler forms of learning like classification or regression. This article builds the agent-environment loop from first principles. It explains what each signal means and how the cycle unfolds over discrete time steps. It shows how to represent it as pseudocode and as a state diagram. It also explains why this framing is both general and tractable. It closes by previewing the concepts that this loop sets up. These include rewards and returns, the Markov property, and the exploration-exploitation dilemma. These ideas are previewed here without yet being resolved.
- Reinforcement learning models sequential decision-making as a loop between an agent and an environment.
- At each discrete time step, the agent observes a state, selects an action, and receives a reward plus a new state.
- The agent's behavior is captured by a policy, a mapping from states to actions (or to action probabilities).
- The agent's objective is to maximize cumulative reward over time, not just the immediate reward.
- The loop is general enough to model robotics, games, recommendation, and control, using the same three signals.
- This cycle is the scaffold on which returns, the Markov property, and exploration strategies are later built.
Reinforcement learning is the study of how an agent should choose actions, based only on states and rewards observed through repeated interaction, in order to maximize long-run cumulative reward.
The idea
The agent-environment loop is the formal interaction protocol of reinforcement learning. Time is divided into discrete steps . At each step , the environment presents the agent with a state , a description of the current situation. The agent, using its internal decision rule, selects an action from the set of actions available in that state. The environment then responds with two things: a numerical reward , a scalar signal indicating how good that action was, and a new state . This produces a sequence of experience:
Everything the agent knows about the world comes through this stream. It never gets a labeled "correct action" the way a supervised learner gets a labeled example. It only gets to see the consequences, in the form of rewards and new states, of the actions it actually chose. The agent's decision rule is called a policy, denoted . A deterministic policy is a function mapping each state to a single action. A stochastic policy is a conditional distribution , giving the probability of choosing each action in each state. Stochastic policies matter because, as later articles on the Exploration-Exploitation Dilemma discuss, always picking the same action can trap an agent in a suboptimal routine; some randomness lets it keep discovering better options. The environment, for its part, is characterized by its dynamics: the (possibly unknown) rule that determines the distribution of and given and . In the cleanest and most widely studied case, this rule depends only on the current state and action, not on the full history — a property called the Markov Property, which will be made precise separately. For now, the loop is defined generally enough to allow environments whose dynamics are deterministic, stochastic, known to the agent, or completely unknown, since RL algorithms differ mainly in what they assume about this. The agent's ultimate goal is not to maximize any single reward , but the cumulative reward over an episode or over time, a quantity formalized later as the return. The loop is simply the mechanism that generates the data — states, actions, rewards — from which the agent must learn to act well.
How it works
The loop is best understood as a synchronous exchange: the environment "moves first" by presenting a state, then the agent moves, then the environment moves again. Concretely, one full episode of interaction unfolds as follows. 1. The environment is initialized, producing an initial state (this may be fixed or drawn from a start-state distribution). 2. At each time step , the agent observes . 3. The agent selects an action according to its policy , either (deterministic) or (stochastic). 4. The environment computes the next reward and next state , based on its (possibly hidden) transition dynamics. 5. The agent receives and may update its internal knowledge (value estimates, policy parameters, etc.). 6. If is a designated terminal state, the episode ends; otherwise the loop returns to step 2 with . Some environments are episodic — they naturally terminate (a chess game ends in checkmate; a maze run ends at the goal) — and some are continuing, running forever without a natural terminal state (a thermostat regulating temperature indefinitely). Both are modeled by the same loop; continuing tasks simply never reach step 6's termination branch, and their return must be handled specially, as discussed under returns. The pseudocode below expresses this cycle in a language-agnostic way that is faithful to how virtually every RL codebase is structured, from tabular Q-learning to deep RL frameworks. ``` procedure RUN-EPISODE(environment, agent, max_steps): state ← environment.RESET() # produces S_0 total_reward ← 0 t ← 0 while state is not TERMINAL and t < max_steps: action ← agent.SELECT-ACTION(state) # A_t ~ π(· | S_t) (next_state, reward, done) ← environment.STEP(action)
# environment computes R_{t+1}, S_{t+1} agent.OBSERVE(state, action, reward, next_state, done)
# agent may update π, value estimates, etc. total_reward ← total_reward + reward state ← next_state t ← t + 1 if done: break return total_reward, t # episode return and length ``` ``` procedure TRAIN(environment, agent, num_episodes): for episode in 1 .. num_episodes: (G, length) ← RUN-EPISODE(environment, agent, max_steps) record G, length for monitoring return agent ``` Two design points deserve emphasis because they are easy to misread on a first pass. First, `environment.STEP(action)` is the only place new information enters the system: the agent cannot query the environment's internal transition rule directly, it can only act and observe the consequence. This is why RL is described as learning from interaction rather than from a fixed dataset. Second, `agent.OBSERVE(...)` is deliberately left abstract: different algorithms (value-based, policy-gradient, model-based) use this experience tuple in very different ways, but they all consume exactly this tuple, no more and no less. This is the common interface that lets the same environment be paired with radically different learning algorithms.
Complexity & correctness
Framed purely as a protocol, the agent-environment loop has no "complexity" in the algorithmic sense of a sorting or search routine — it is a specification of an interface, not an algorithm that solves a problem. What we can analyze honestly is the per-step cost of running the loop, and the soundness of the framing, i.e. why this loop is an adequate model of sequential decision-making.
Per-step cost. Each iteration of `RUN-EPISODE` performs exactly one call to `agent.SELECT-ACTION`, one call to `environment.STEP`, and one call to `agent.OBSERVE`. If these calls run in , , and time respectively (where depend on the specific policy representation, environment simulator, and learning update used), then one loop iteration costs , and an episode of length costs . For a tabular policy over a small discrete state-action space, and are (array lookups/updates); for a deep-RL agent, and involve a forward and/or backward pass through a neural network, costing time proportional to the number of network parameters. The environment step cost is entirely determined by the simulator or physical system and is outside the agent's control. Space cost is per step if the agent discards old transitions immediately (as in pure online learning), or if it stores the last transitions in a replay buffer, a pattern used by many deep-RL methods.
Correctness — in what sense is the loop "correct"? There is no theorem to prove about the loop itself; instead, correctness here means the loop faithfully and losslessly represents the information available to a sequential decision maker. Two invariants justify this: 1. Information invariant. At time , everything the agent has ever observed is exactly the history . The pseudocode enforces this by construction: `agent.SELECT-ACTION` is only ever given `state`, and any additional memory the agent wants (e.g. past states) must be explicitly stored inside the agent object, never smuggled in from the environment. This makes explicit exactly what "learning from experience" means: the agent's policy at time can be any function of , but nothing more. 2. Causal invariant. The reward and next state are functions (possibly stochastic) only of and as realized at time — they cannot depend on future actions the agent has not yet taken. This rules out "cheating" loops where the environment reveals information from the future, and matches how physical and computational systems actually behave: cause precedes effect. Formally, the environment defines a (possibly unknown) joint distribution , and the loop is simply repeated sampling from this conditional distribution, driven by the agent's chosen actions.
Honest tradeoffs. The loop's generality is also its main limitation. Because it makes almost no assumptions about , the loop alone gives no algorithm for computing good actions — it only defines the data agents can use. Efficient learning requires additional structure, most commonly the Markov property (dynamics depend only on the current state, not full history), which is what allows compact value-function and policy representations rather than ones that must condition on ever-growing histories . Without some such assumption, the state space of "possible histories" grows without bound, and no tractable algorithm exists in general; this is precisely the gap that the Markov Property article closes.
Worked example
Consider a minimal but non-trivial environment: a grid world, states labeled , where the agent starts at state (the middle) and can move `LEFT` or `RIGHT`. State gives a reward of and ends the episode; state gives a reward of and ends the episode; all other transitions give reward (a small cost for taking time). This is deliberately asymmetric — the left exit is worth more than the right exit, but is one step farther away — so the "obvious" shortest path is not automatically the best one, which is exactly the kind of subtlety cumulative-reward reasoning must resolve. Suppose the agent follows a fixed deterministic policy: always move `LEFT`. Trace the loop:
| terminal? | |||||
|---|---|---|---|---|---|
| 0 | 2 | LEFT | −1 | 1 | no |
| 1 | 1 | LEFT | −1 | 0 | no |
| 2 | 0 | — | +5 | (episode ends) | yes |
The episode length is steps of environment interaction (two moves plus the terminal reward), and the total reward collected is . Now compare against always moving `RIGHT`:
| terminal? | |||||
|---|---|---|---|---|---|
| 0 | 2 | RIGHT | −1 | 3 | no |
| 1 | 3 | RIGHT | −1 | 4 | no |
| 2 | 4 | — | +1 | (episode ends) | yes |
Total reward here is . Even though both policies take the same number of steps, moving `LEFT` accumulates strictly more total reward, versus , because the left terminal reward outweighs the step costs. This is exactly why an RL agent cannot be greedy about immediate reward alone (both single steps here give , tying) — it must reason about the cumulative consequence of a whole action sequence, which is the motivation for the return, defined in the next stage of this material. Note also that nothing in the loop itself told the agent which policy is better; the loop only generated the trace. Discovering that `LEFT` is superior — and doing so without exhaustively trying every deterministic policy — is precisely the job of the value-function and control algorithms built on top of this loop.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Treating the environment as a labeled dataset | Confusing RL with supervised learning; assuming there's a "correct action" per state | Remember: only reward and next-state are observed, never the optimal action directly |
| Letting the agent see future rewards/states | Implementation bug where the environment leaks lookahead information | Enforce that `STEP(action)` only uses , never or later data, when generating |
| Off-by-one in reward indexing | Writing instead of for the reward caused by | Fix the convention: the reward caused by is indexed , matching |
| Forgetting to reset state between episodes | Reusing stale `state` variable across `RUN-EPISODE` calls | Always call `environment.RESET()` at the start of every episode |
| Ignoring episode termination in continuing tasks | Applying episodic-style total-reward reasoning to a never-ending task | Use discounted or average-reward formulations, covered under returns, for continuing tasks |
| Assuming the agent's policy is history-independent when it isn't Markov | Building a tabular policy on raw non-Markov states | Either augment the state (e.g. add memory) or use a Markov-compliant state representation |
Pioneers & history
The agent-environment loop as a formal object emerged from the confluence of animal learning psychology, optimal control theory, and computer science. Its modern textbook form is due most directly to Richard S. Sutton and Andrew G. Barto, whose synthesis of trial-and-error learning (rooted in psychology) with the mathematics of optimal control (rooted in engineering) gave reinforcement learning its unified vocabulary of states, actions, rewards, and policies.
Origins · 1 minRichard S. Sutton and how this was discovered
Where this matters
The agent-environment loop is not an abstraction confined to textbooks; it is the literal software interface used across modern RL systems. The OpenAI Gym / Gymnasium API, arguably the most widely used RL benchmarking interface, implements exactly the `reset()` / `step(action)` pattern shown in the pseudocode above, and nearly every published RL algorithm is built to plug into that interface. DeepMind's AlphaGo and AlphaZero cast board-game play as this loop, with the board position as state, legal moves as actions, and win/loss as terminal reward. Autonomous vehicle stacks use variants of this loop in simulation to train and evaluate driving policies before any real-world deployment. Data center cooling systems, such as those reported by Google, treat sensor readings as state, fan/cooling adjustments as actions, and energy savings as reward. Recommendation systems at scale (video, e-commerce, ads) frame user sessions as episodes, recommended items as actions, and engagement signals as reward, learning policies entirely from this same interaction stream. In every one of these systems, whatever the learning algorithm — value-based, policy-gradient, model-based, or a hybrid — the underlying loop of observe-act-reward-observe is identical, which is exactly why understanding it precisely, independent of any specific algorithm, is the foundational step in reinforcement learning.
Ask the tutor: How does adding the Markov property to this loop change what algorithms can guarantee about optimal behavior?
Is the agent-environment loop the same thing as a Markov Decision Process (MDP)?
Not quite. The loop is the general interaction protocol: states, actions, rewards, exchanged over discrete time steps, with no assumption about how the environment's dynamics depend on history. An MDP is a specific, stronger mathematical structure that additionally assumes the Markov property, meaning the next state and reward depend only on the current state and action, not the full history. Every MDP can be run through the agent-environment loop, but the loop itself is more general and can describe non-Markov environments too, where the agent may need memory of past observations to act well. The Markov Property article makes this distinction precise.
Does the agent need to know the environment's transition dynamics to use this loop?
No, and this is one of the loop's most important features. The agent only needs access to the interaction interface: it observes a state, submits an action, and receives a reward and next state. The underlying probability distribution over outcomes, sometimes written , can be completely unknown to the agent. Algorithms that never learn or use this distribution explicitly are called model-free; algorithms that estimate it and plan with it are called model-based. Both categories operate through exactly the same agent-environment loop.
What counts as a "reward" — does it have to be money or points?
A reward is simply a real number the environment emits at each time step, chosen by whoever designs the task to encode what "success" means. It might be a game score, a physical distance traveled, negative energy consumption, or an artificial shaping signal. Designing rewards well, so that maximizing them actually produces the behavior you want, is a genuinely hard and important problem called reward design, but it is separate from the loop itself, which only requires that the signal be a scalar emitted at every step.
Can the same action be legal in one state but not another?
Yes. The action set is often written to emphasize that available actions can depend on the current state. In chess, legal moves depend entirely on the board position; in a grid world, moving `LEFT` from the leftmost cell may be disallowed or simply have no effect. The loop accommodates this naturally: the agent's policy only needs to assign probability, or select deterministically, among the actions actually available in the observed state.
Why is the reward received one step delayed, written as R_{t+1} rather than R_t?
This indexing is a convention that keeps the causal story unambiguous. At time the agent is in state and chooses action ; the environment then computes a consequence of that state-action pair, which is delivered as the pair . Writing the reward with subscript makes clear it is generated after and because of , not something the agent already knew when choosing . Some texts alternately index the reward as ; what matters far more than the specific convention is that a course or codebase is internally consistent about it.
How does this loop relate to the exploration-exploitation dilemma?
The loop explains how information flows, but says nothing about how the agent should choose actions to learn efficiently. Because the agent only observes consequences of actions it actually takes, it faces a genuine dilemma: it can exploit its current best-known action to gather high reward now, or explore a less-certain action to potentially discover something better for the future. This tension, and strategies for managing it, is exactly the subject of the Exploration-Exploitation Dilemma, which builds directly on the state-action-reward cycle defined here.
Is the agent-environment loop only relevant to "toy" problems like grid worlds?
No — grid worlds are useful teaching examples precisely because the loop scales unchanged to vastly more complex settings. The same state-action-reward cycle underlies Atari-playing deep Q-networks, robotic control policies trained in physics simulators, large-language-model fine-tuning via reinforcement learning from human feedback, and industrial control systems. What changes across these settings is the complexity of the state and action spaces and the sophistication of the learning algorithm plugged into `SELECT-ACTION` and `OBSERVE` — the loop's structure itself remains identical.