Why Dictionary Observation Spaces and Custom Reward Wrappers Are the Right Primitives When API Responses Are Your Environment Signal
Dictionary spaces and reward wrappers preserve API structure and make success definitions explicit.

Gymnasium provides tools for building custom RL environments around API responses, including spaces.Dict, [ObservationWrapper](https://gymnasium.farama.org/api/wrappers/observation_wrappers/), and RewardWrapper. Dictionary observation spaces preserve the structure of what an agent can see, while custom reward wrappers make the meaning of success explicit. These primitives work together only when they share an API contract backed by stateful simulation, deliberate fault handling, and continuous verification against the live API.
Why API responses resist flat encoding
A Stripe PaymentIntent response has a payment’s status and amount, and the API exchange around it has HTTP status codes and may have error details. A Kalshi order-book snapshot contains a market ticker and nested yes/no bid prices. Field names, types, and nesting distinguish information that serves different purposes, while pagination cursors and rate-limit headers add context beyond the main response body.
Flattening these documents into a Box makes those distinctions depend on an external positional encoding. A field is known by its place in an array, and its type must fit the same numerical representation as the other types. That mapping is fragile when the API changes. An array can keep its expected shape even when a position no longer means what the policy learned it meant. Flattening risks losing the declared relationship between an API field and the observation derived from it, a loss that numerical computation itself does not require.
What spaces.Dict actually declares and why that matters
spaces.Dict makes that relationship part of the environment interface. It declares named fields, each with sub-spaces that set their own rules for valid types, shapes, and values. Each field has an explicit place in the contract. A status can use Discrete(3), an amount can use a Box bounded from zero to 1e6, and a cursor can use Text. This illustrative mapping preserves distinctions that an anonymous float array leaves to separate documentation.
Gymnasium: A Standardized Interface for Reinforcement Learning Environments distinguishes fundamental spaces from composite spaces that combine data through nesting. Its fundamental spaces include Box, Discrete, MultiBinary, MultiDiscrete, and Text, while its composite spaces include Tuple, Dict, Sequence, Graph, and OneOf. Nesting is the structural advantage for API environments. In a Kalshi order-book observation, the market ticker and the yes/no bid prices can occupy separate sub-spaces, with asks understood as the complement of the opposite side’s best bid.
The declaration also supplies a surface for validation. An unexpected field or an out-of-range value can be caught before it becomes training input, provided the environment actually checks observations against the declaration. ObservationWrapper keeps parsing, filtering, and typing apart from the API call layer, so the base environment need not handle every change to an observation. When that transformation changes the observation’s shape, the wrapper’s observation_space must describe the transformed result.
How RewardWrapper maps API outcomes onto the scalar the agent optimizes
HTTP codes, payment transitions, error envelopes, and timing metadata express distinct outcomes, but the learning algorithm optimizes a scalar. Interpretation is therefore unavoidable, and it must be explicit. An HTTP exchange can succeed even when the agent has not finished the intended task, and failed exchanges can call for different penalties.
In a Stripe payment flow, the reward definition can assign partial credit for valid PaymentIntent creation, zero for a 400 response, a penalty for a 429, and full reward for a completed charge. The weights express the actual training objective. If partial progress becomes easier to collect than completion, the scalar can favor behavior that satisfies the reward definition without satisfying its author’s intent.
RewardWrapper provides a separate layer for applying that interpretation. Subclassing it and overriding reward() transforms the reward returned by a step before the learning algorithm receives it. Its interface is narrower than the whole API exchange. Because reward() receives the reward rather than the response document, shaping based on the response needs an explicit link in the environment design to the information about the outcome.
This separation makes reward logic independently testable and replaceable. ObservationWrapper, RewardWrapper, and ActionWrapper are composable layers, so a change in shaping need not require a change in the API call layer. But the observation and reward layers still need to agree on what each outcome means.
Why the observation space and reward wrapper must be co-designed against the same API contract
A reward can distinguish outcomes that an observation has collapsed. Suppose the reward wrapper grants success for a 201 response, but the observation exposes only a binary ok/not_ok field. The reward distinguishes evidence the observation has erased. The agent may obtain success without being able to identify the response code responsible for it, leaving the observation contract weaker than the objective it is supposed to support.
This is a design-induced form of partial observability. The observation represents what the agent can see of the potentially fuller underlying state, so omitted information requires deliberate treatment. Fields that tell rewarded outcomes apart should be in the declared observation, while metadata used only for diagnostics can stay outside the agent’s input.
The shared source of truth should be the API’s JSON schema or OpenAPI specification. Deriving the dictionary declaration and the reward logic’s field references from that source makes a renamed field or changed type a common contract problem, preventing the two from drifting separately. Gymnasium enables this discipline but does not enforce it. Its standard interface covers spaces, step and reset behavior, and auxiliary diagnostic information, while the engineering contract must also settle units, normalization, history length, action bounds, masks, projection behavior, and reward definitions.
Stateful simulation is the prerequisite that makes both primitives meaningful across a multi-step trajectory
Even when the observation and reward designs work together, they fail if each simulated response ignores earlier actions. A correctly typed PaymentIntent observation is insufficient when a mock returns the same hardcoded document whether or not a prior POST created the intent. What the agent sees in step 7 must reflect the relevant consequences of what it did in step 3.
Static mocks and stateful simulators differ at precisely this point. A static mock returns the same response for a given request, but a stateful simulator remembers what changed across calls. Adding, listing, and deleting a record must all update the same simulated world. Without that continuity, a successful response can appear to confirm an action whose consequences never become observable, breaking the connection between progress and reward.
For the Kalshi trading example, a limit order placed in step 2 must appear in the order-book observation in step 5, and a cancel in step 6 must remove it. That sequence tests more than response formatting. It tests whether later observations reflect earlier actions. In MDP terms, the transition function describes how an action moves the world from its current state, so the response depends on both the state and the action. A stateless mock removes that dependence and teaches the policy a different transition system.
Fault injection as a first-class dimension of reward wrapper design
State continuity is necessary, but a simulator that preserves state only on successful requests still omits part of the operating environment. Real API exchanges include rate limits, token expiry, network failures, and malformed responses. Those outcomes also require explicit reward semantics. A success-only wrapper leaves how the agent should act when requests fail out of the objective’s design, even though it will face those failures in production.
A 429 with a Retry-After header illustrates why the distinction must extend beyond the response code. The wrapper should treat a patient retry positively or neutrally and penalize an immediate retry, rather than teaching the agent to hammer the rate limit. Timing becomes part of the decision evidence. If retry timing affects reward, the observation contract must expose the information needed to distinguish those choices, and the simulator must preserve the corresponding conditions across steps.
A 401 invalid_grant mid-trajectory calls for a different response. The agent should surface a needs_reauth state, and the reward definition should recognize the reauthentication action and discourage further retries. A truncated stream requires another explicit distinction. The observation needs a stream-completeness field, and the wrapper must penalize acting on a partial observation.
Latency, 429s, 503s, and token expiry should be triggerable deterministically in CI so each observation and reward path can be exercised deliberately. The fault dimensions belong in the contract because they define conditions under which both the observation and the reward must retain their intended meaning.
Verification drift: how an unverified simulator corrupts the observation contract silently
A simulator can pass its own tests even after it stops matching the live API. If an upstream field is renamed, an enum tightened, or a required header added, the simulated response may remain valid under an obsolete local declaration. Internal consistency does not establish external fidelity. The policy can continue learning from observations that pass local checks but no longer match the environment in which it must act.
Schema drift is the most direct version of this failure. A changed field name, type, or required status makes the dictionary declaration stale, while an unversioned tool-parameter change can invalidate the shape an agent learned. Behavioral drift is less visible to structural validation. If Kalshi changes how order fills are reported, a field can retain its type while acquiring a meaning the reward wrapper no longer interprets correctly. The observation may pass validation even as the reward assigns credit on the wrong basis.
LLM tool-use environments add model-version drift to that problem. The brief identifies provider changes to an underlying model even when a dated identifier has been pinned. Continuous verification against the live API must address both response structure and behavior, because checking only one leaves the other free to diverge. The contract version also needs to identify the API version against which the simulator was verified.
Putting it together: the environment contract as the design document for an API-backed RL system
The environment contract joins these decisions into one specification. Its observation definition maps API fields to typed dictionary sub-spaces and records shape, units, normalization, and history length. Reward-relevant evidence belongs in that declared view. Its action definition sets out the bounds, masks, and projection behavior, and its transition requirements say how actions change the simulated world from one call to the next. Together, those definitions describe what the agent can distinguish and what its actions can change.
The reward definition then specifies how those changes become an objective. It needs explicit treatment of 2xx, 4xx, 429, 5xx, and timeout outcomes rather than an implicit zero for cases nobody considered. Diagnostic metadata has a separate, declared role. The info dictionary can retain raw request IDs, headers, or pagination metadata outside the policy input, but information needed for a rewarded decision must also be represented in the observation. Any route by which the reward wrapper uses that metadata must be explicit.
Finally, the contract sets out the deterministic fault dimensions and the simulator’s claim to match the live API. This makes the wrapper’s interpretation auditable and ties its tests to the conditions the agent will encounter. The contract is a living design document. When the API changes, the observation mapping, reward logic, and simulated transitions must be reconsidered together, with continuous verification providing the evidence that the declared environment still matches the real one.


