An Agent in an Environment with a Verifiable Task
We are moving from design to an operational program. It will evaluate the target, learn its own control, and select additional surveillance based on its cost. All these functions have already been prepared in the previous chapters. The first pass can be done without changing the code: understand the problem, write down the prediction and reproduce the finished run. Own new conditions appear after checking the original result.
The first agent on a regular computer
Open the workshop directory and find the agent_lab.py file. We have before us a small agent who chooses an action under conditions of incomplete information. All his work is available for viewing: what information was received, what was retained in memory, how the assumption changed and what forecast was made before the action. This is a convenient starting point for designing more complex systems. We can change one mechanism and observe the consequences without relying on the verisimilitude of the program's verbal response.
You don't need to understand every line of Python to get started. First, analyze the problem and predict the result. Then run the finished program, compare the expectation with the numbers, and only then proceed to implementation. The code here serves as an accurate record of the model. It can be read gradually: inputs, status, update, action, feedback. These five questions will help you understand even an unfamiliar program.
The installation app provides commands for Windows, macOS, and Linux. Requires Python version 3.10 or later. The program uses the standard library, runs locally and does not require an API. In the directory with the file, run the command below. On Windows, replace python3 with py -3 if your installation uses this launcher.
python3 agent_lab.py --steps 1000 --runs 30 --seed 1729 --json my_results.json
The steps parameter sets the number of steps of one script, runs — the number of repetitions, seed — the initial value of the randomness generator. The last parameter specifies the result file. With the same parameters, the program repeats the same computational experiment. This helps test code changes, but other scenarios are needed to evaluate robustness.
How the environment works
At each step there is a target to the left or to the right. The agent does not see it directly. Between adjacent steps, the side is preserved with probability 0.95. Therefore, recent information is usually useful, although sometimes it is outdated. The usual observation correctly indicates the side in 75 percent of cases and is missing in a quarter of the steps. For a small price you can get additional observation with an accuracy of 90 percent.
The agent sends a left or right command. In the first half of the scenario it usually causes an effect on the corresponding side, and in the second half the connection is inverted. A single motor error with probability 0.05 also changes the effect. This creates two different sources of uncertainty: where the target is and what will happen after the command. Reliable goal perception will not help if the control model is outdated.
The rule changes from step 501 at a thousand steps. The experimenter knows this. The agent receives neither a switch flag, nor a schedule, nor a true target, nor a seed. After the command, a visible effect is available to him. Success information is calculated by the environment and returned to the researcher after the script completes.
Why not transfer success to the agent immediately? In a given binary problem, the combination of a known effect and success would reveal the true goal. Then memory and noisy observation would be tested in a different information situation. The prohibition relates to a specific research model. In another problem, correctness feedback may be a legitimate part of the interface, as in the strategy review work in chapter 30.
Figure 62. Two circuits of one agent. Training diagram of the interface of the first work. Observation updates the belief about the goal, and the visible effect of the command is the control model. The true goal, the moment of the rule change, and the current success are not included in the information available to the agent. An additional paid request provides another observation of the target and is not shown separately for clarity.
Memory in the form of probabilistic belief
The target_right_probability state stores the probability of the right target according to the current model. The number 0.8 means that, given the given premises and observations, the right side is considered more likely. This is a model statement that may be wrong. The true position is not included in the calculation.
Before making a new observation, the agent takes into account the possibility of the target moving. If the probability of the right side was 0.8, and the target persists with probability 0.95, the following prediction is obtained from two possibilities: the target was on the right and stayed there, or was on the left and moved. Their probabilities add up. In this example, the new forecast is 0.77. Observation then refines it using Bayes' rule.
old_belief = 0.8
stay = 0.95
prior = stay * old_belief + (1 - stay) * (1 - old_belief)
print(prior) # 0.77
The memory here does not represent a detailed autobiography. The past is compressed into a single number, the sufficiency of which is determined by the chosen probabilistic model. This storage method allows the causal contribution of history to be clearly shown. If an observation is missed, the agent still has a prediction; if history is disabled, the initial belief about the goal reverts to 0.5.
The second variable, direct_mapping_probability, estimates the likelihood of a command being directly associated with an effect. After the action, the agent compares the command with the visible result. The discrepancy may be due to a motor error or a change in control. Bayesian updating changes their relative plausibility. The model allows for a small probability of a link change at each step and is therefore able to revise a previously reliable assumption.
Why measure success before taking action?
From the two beliefs, the probability of success for each command can be calculated. The agent combines options for the target position and possible effect, selects the more promising command, and writes down a prediction before acting. If you record confidence after receiving the correct answer, the indicator no longer reflects previous uncertainty.
An additional observation is purchased when the expected improvement of the current solution exceeds the price. The program considers both possible sensor responses, recalculates the belief for each, and averages the best expected result. This is a calculation of immediate benefit. The future value of information in the next steps is not separately planned, so we do not call such a policy optimal for all possible horizons.
Cost is needed to differentiate between accuracy and usefulness. Getting more information is sometimes beneficial, but it depends on its price and whether it helps change action. If the main uncertainty is related to management, further clarification of the goal may do little to improve the solution. The state of the world and the state of one's own action model should be taken into account together.
Figure 63. The conditional value of additional observation. Calculation according to agent_lab.py rules for the selected training state at the first missing observation; These are not average launch results. Both possible answers give the expected success of 0.788, so the gain of 0.288 exceeds the price of 0.08. If the probability of direct command communication is 0.5, knowledge of the goal in itself does not improve the choice of action.
Four modes and a fair comparison
Full mode uses all the described mechanisms. No_world_memory only disables the transfer of goal beliefs between steps. Action model learning is preserved. In fixed_action_model, the forward link probability remains equal to the original 0.90, without updating. No_extra_query prohibits the purchase of additional observations. This precise description is important: the name of the mode alone does not explain what calculations were changed.
All modes receive the same potential observations and motor errors for the corresponding scenario. The randomness is divided into independent threads, and the values are pre-prepared. Buying an observation unlocks additional value without shifting subsequent random events. Different commands may produce different effects, but the motor distortion at this step is common.
The attached run runs thirty scenarios with one thousand steps for each mode. These are actual program results, not human or animal data. The request price is 0.08; success brings one, failure brings zero. The utility is obtained after subtracting the query costs.
Mode | Success percentage | Utility per step | Brier |
Full | 87.94 | 0.8619 | 0.1054 |
Without the memory of the world | 85.36 | 0.7767 | 0.1202 |
Fixed Action Model | 49.97 | 0.4841 | 0.3444 |
No additional request | 77.91 | 0.7791 | 0.1589 |
Brier is the average of the squared difference between the predicted success and the actual outcome, written as zero or one. A lower value means a more accurate probabilistic forecast. It depends on both the calibration and the information content of the forecasts. To call it a pure measure of calibration, self-awareness, or quality of experience would be a mistake.
The overall success of the fixed model of about half hides the sharp difference between the two periods: 87.80 percent before the inversion and 12.13 percent after it. The full mode has the corresponding percentage values 88.06 and 87.83. To measure the rate of retraining, short time windows are needed: the average of the entire second half smooths out the transition process.
There is also a less obvious comparison. The version without memory is more accurate than the version without queries, but it buys significantly more information. As a result, its utility is slightly lower. Therefore, the phrase “this agent is better” requires specifying a criterion. The accuracy of the answer, the cost and the reliability of the forecast may vary in different ways.
Figure 64. Success and usefulness answer different questions. Results of the agent_lab.py program: 30 general random scenarios for 1000 steps, seed 1729. The average of the two periods is shown on the left, rather than the rate of adaptation within the period. On the right, the cost of additional requests is subtracted from success. Data: lab01_results.json.
How to read one agent step
First, the agent takes into account the possible movement of the target in the stored belief. It then obtains the available noisy signal and updates the estimate. From the uncertainty of the goal and control, it calculates the utility of the commands and the possible request. The prediction of success is written down before the action. After the command, the visible effect updates the control model. The evaluator does not reveal the true goal, inversion schedule and current success to the agent. In this binary task, success along with the effect would reveal the target and change the interface being explored.
What has now been established
We know the order of information and can distinguish prediction from late knowledge. Mode numbers now need to be read along with the asking price and the period before or after the inversion.
Figure 65. Uncertainty of differences between modes. The result of the analysis of the attached data. Dots are average paired utility differences; intercepts are approximate 95 percentile intervals from 4000 repeated samples of 30 entire scenarios. The unit of repetition is the script. Intervals refer to individual comparisons and do not provide a joint guarantee of 95 interest. Data: paired_analysis.json.
Practice 28 Predict the outcome of environmental changes
Why do it: Reproduce the basic work and explain one result through the design of the mechanism.
What you will need: Probabilistic models of the world and action, Brier score and independent repetition unit. The workshop uses Python 3.10 or later and the standard library.
Time reference: 30–45 minutes. Can be done intermittently; This is not a speed standard.
1. Unpack the practice and run python run_practice.py --self-test. Before the main run, write down the expected behavior of the fixed and learning model after a change in control.
2. Run python run_practice.py --lab 1. Save the created directory, parameters and checksums.
3. In the results table, separately compare the success before and after the switch, the utility per step, and the quality of the prediction. Do not select the best mode without specifying the indicator.
4. Trace one episode through the log: available observation, previous state, forecast, command, visible effect, new state.
What to save: Saved run and short output with mechanism, indicator and condition area.
Hint: The mode without world memory is still learning the connection between the command and the effect. A specific function is disabled, not the entire ability to store the past.
Exploratory continuation: Change exactly one condition by formulating a prediction in advance: request price, sensor reliability, or target variability. Then repeat the comparison on new scenarios.
Analysis and answers - Appendix F, chapter 28, p. 293
Self-test
1. Why does memoryless mode retain learning of the command's connection to the effect?
2. Why is the overall success of a fixed agent misleading without period separation?
3. What would change if you gave the agent the correct answer before recording the belief?
The first agent showed the two beliefs working together. Now let's separately check the presentation device, reprocessing and transmission of content, without confusing them with the success of the entire system.
Chapter 29



