File size: 39,676 Bytes
c8e832f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
# OpenEnv: Production RL Made Simple

<div align="center">

<img src="https://upload.wikimedia.org/wikipedia/commons/1/10/PyTorch_logo_icon.svg" width="200" alt="PyTorch">

### *From "Hello World" to RL Training in 5 Minutes* โœจ

---

**What if RL environments were as easy to use as REST APIs?**

That's OpenEnv. Type-safe. Isolated. Production-ready. ๐ŸŽฏ

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/meta-pytorch/OpenEnv/blob/main/examples/OpenEnv_Tutorial.ipynb)
[![GitHub](https://img.shields.io/badge/GitHub-meta--pytorch%2FOpenEnv-blue?logo=github)](https://github.com/meta-pytorch/OpenEnv)
[![License](https://img.shields.io/badge/License-BSD%203--Clause-green.svg)](https://opensource.org/licenses/BSD-3-Clause)
[![PyTorch](https://img.shields.io/badge/PyTorch-EE4C2C?logo=pytorch&logoColor=white)](https://pytorch.org/)

Author: [Sanyam Bhutani](http://twitter.com/bhutanisanyam1/)

</div>

---

## Why OpenEnv?

Let's take a trip down memory lane:

It's 2016, RL is popular. You read some papers, it looks promising. 

But in real world: Cartpole is the best you can run on a gaming GPU. 

What do you do beyond Cartpole?

Fast-forward to 2025, GRPO is awesome and this time it's not JUST in theory, it works well in practise and is really here!

The problem still remains, how do you take these RL algorithms and take them beyond Cartpole?

A huge part of RL is giving your algorithms environment access to learn. 

We are excited to introduce an Environment Spec for adding Open Environments for RL Training. This will allow you to focus on your experiments and allow everyone to bring their environments.

Focus on experiments, use OpenEnvironments, and build agents that go beyond Cartpole on a single spec.

---

## ๐Ÿ“‹ What You'll Learn

<table>
<tr>
<td width="50%">

**๐ŸŽฏ Part 1-2: The Fundamentals**

- โšก RL in 60 seconds
- ๐Ÿค” Why existing solutions fall short
- ๐Ÿ’ก The OpenEnv solution

</td>
<td width="50%">

**๐Ÿ—๏ธ Part 3-5: The Architecture**

- ๐Ÿ”ง How OpenEnv works
- ๐Ÿ” Exploring real code
- ๐ŸŽฎ OpenSpiel integration example

</td>
</tr>
<tr>
<td width="50%">

**๐ŸŽฎ Part 6-8: Hands-On Demo**

- ๐Ÿ”Œ Use existing OpenSpiel environment
- ๐Ÿค– Test 4 different policies
- ๐Ÿ‘€ Watch learning happen live

</td>
<td width="50%">

**๐Ÿ”ง Part 9-10: Going Further**

- ๐ŸŽฎ Switch to other OpenSpiel games
- โœจ Build your own integration
- ๐ŸŒ Deploy to production

</td>
</tr>
</table>

!!! tip "Pro Tip"
    This notebook is designed to run top-to-bottom in Google Colab with zero setup!

    

    โฑ๏ธ **Time**: ~5 minutes | ๐Ÿ“Š **Difficulty**: Beginner-friendly | ๐ŸŽฏ **Outcome**: Production-ready RL knowledge


---

## ๐Ÿ“‘ Table of Contents

### Foundation

- [Part 1: RL in 60 Seconds โฑ๏ธ](#part-1-rl-in-60-seconds)
- [Part 2: The Problem with Traditional RL ๐Ÿ˜ค](#part-2-the-problem-with-traditional-rl)
- [Part 3: Setup ๐Ÿ› ๏ธ](#part-3-setup)

### Architecture

- [Part 4: The OpenEnv Pattern ๐Ÿ—๏ธ](#part-4-the-openenv-pattern)
- [Part 5: Example Integration - OpenSpiel ๐ŸŽฎ](#part-5-example-integration---openspiel)

### Hands-On Demo

- [Part 6: Interactive Demo ๐ŸŽฎ](#part-6-using-real-openspiel)
- [Part 7: Four Policies ๐Ÿค–](#part-7-four-policies)
- [Part 8: Policy Competition! ๐Ÿ†](#part-8-policy-competition)

### Advanced

- [Part 9: Using Real OpenSpiel ๐ŸŽฎ](#part-9-switching-to-other-games)
- [Part 10: Create Your Own Integration ๐Ÿ› ๏ธ](#part-10-create-your-own-integration)

### Wrap Up

- [Summary: Your Journey ๐ŸŽ“](#summary-your-journey)
- [Resources ๐Ÿ“š](#resources)

---

## Part 1: RL in 60 Seconds โฑ๏ธ

**Reinforcement Learning is simpler than you think.**

It's just a loop:

```python

while not done:

    observation = environment.observe()

    action = policy.choose(observation)

    reward = environment.step(action)

    policy.learn(reward)

```

That's it. That's RL.

Let's see it in action:

```python

import random



print("๐ŸŽฒ " + "="*58 + " ๐ŸŽฒ")

print("   Number Guessing Game - The Simplest RL Example")

print("๐ŸŽฒ " + "="*58 + " ๐ŸŽฒ")



# Environment setup

target = random.randint(1, 10)

guesses_left = 3



print(f"\n๐ŸŽฏ I'm thinking of a number between 1 and 10...")

print(f"๐Ÿ’ญ You have {guesses_left} guesses. Let's see how random guessing works!\n")



# The RL Loop - Pure random policy (no learning!)

while guesses_left > 0:

    # Policy: Random guessing (no learning yet!)

    guess = random.randint(1, 10)

    guesses_left -= 1

    

    print(f"๐Ÿ’ญ Guess #{3-guesses_left}: {guess}", end=" โ†’ ")

    

    # Reward signal (but we're not using it!)

    if guess == target:

        print("๐ŸŽ‰ Correct! +10 points")

        break

    elif abs(guess - target) <= 2:

        print("๐Ÿ”ฅ Warm! (close)")

    else:

        print("โ„๏ธ  Cold! (far)")

else:

    print(f"\n๐Ÿ’” Out of guesses. The number was {target}.")



print("\n" + "="*62)

print("๐Ÿ’ก This is RL: Observe โ†’ Act โ†’ Reward โ†’ Repeat")

print("   But this policy is terrible! It doesn't learn from rewards.")

print("="*62 + "\n")

```

**Output:**
```

๐ŸŽฒ ========================================================== ๐ŸŽฒ

   Number Guessing Game - The Simplest RL Example

๐ŸŽฒ ========================================================== ๐ŸŽฒ



๐ŸŽฏ I'm thinking of a number between 1 and 10...

๐Ÿ’ญ You have 3 guesses. Let's see how random guessing works!



๐Ÿ’ญ Guess #1: 2 โ†’ โ„๏ธ  Cold! (far)

๐Ÿ’ญ Guess #2: 10 โ†’ ๐ŸŽ‰ Correct! +10 points



==============================================================

๐Ÿ’ก This is RL: Observe โ†’ Act โ†’ Reward โ†’ Repeat

   But this policy is terrible! It doesn't learn from rewards.

==============================================================

```

---

## Part 2: The Problem with Traditional RL ๐Ÿ˜ค

### ๐Ÿค” Why Can't We Just Use OpenAI Gym?

Good question! Gym is great for research, but production needs more...

| Challenge | Traditional Approach | OpenEnv Solution |
|-----------|---------------------|------------------|
| **Type Safety** | โŒ `obs[0][3]` - what is this? | โœ… `obs.info_state` - IDE knows! |
| **Isolation** | โŒ Same process (can crash your training) | โœ… Docker containers (fully isolated) |
| **Deployment** | โŒ "Works on my machine" ๐Ÿคท | โœ… Same container everywhere ๐Ÿณ |
| **Scaling** | โŒ Hard to distribute | โœ… Deploy to Kubernetes โ˜ธ๏ธ |
| **Language** | โŒ Python only | โœ… Any language (HTTP API) ๐ŸŒ |
| **Debugging** | โŒ Cryptic numpy errors | โœ… Clear type errors ๐Ÿ› |

### ๐Ÿ’ก The OpenEnv Philosophy

**"RL environments should be like microservices"**

Think of it like this: You don't run your database in the same process as your web server, right? Same principle!

- ๐Ÿ”’ **Isolated**: Run in containers (security + stability)
- ๐ŸŒ **Standard**: HTTP API, works everywhere
- ๐Ÿ“ฆ **Versioned**: Docker images (reproducibility!)
- ๐Ÿš€ **Scalable**: Deploy to cloud with one command
- ๐Ÿ›ก๏ธ **Type-safe**: Catch bugs before they happen
- ๐Ÿ”„ **Portable**: Works on Mac, Linux, Windows, Cloud

### The Architecture

```

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”

โ”‚  YOUR TRAINING CODE                                        โ”‚

โ”‚                                                            โ”‚

โ”‚  env = OpenSpielEnv(...)        โ† Import the client      โ”‚

โ”‚  result = env.reset()           โ† Type-safe!             โ”‚

โ”‚  result = env.step(action)      โ† Type-safe!             โ”‚

โ”‚                                                            โ”‚

โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

                  โ”‚

                  โ”‚  HTTP/JSON (Language-Agnostic)

                  โ”‚  POST /reset, POST /step, GET /state

                  โ”‚

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”

โ”‚  DOCKER CONTAINER                                          โ”‚

โ”‚                                                            โ”‚

โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”         โ”‚

โ”‚  โ”‚  FastAPI Server                              โ”‚         โ”‚

โ”‚  โ”‚  โ””โ”€ Environment (reset, step, state)         โ”‚         โ”‚

โ”‚  โ”‚     โ””โ”€ Your Game/Simulation Logic            โ”‚         โ”‚

โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜         โ”‚

โ”‚                                                            โ”‚

โ”‚  Isolated โ€ข Reproducible โ€ข Secure                          โ”‚

โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

```

!!! info "Key Insight"
    You never see HTTP details - just clean Python methods!


    ```python

    env.reset()    # Under the hood: HTTP POST to /reset

    env.step(...)  # Under the hood: HTTP POST to /step

    env.state()    # Under the hood: HTTP GET to /state

    ```


    The magic? OpenEnv handles all the plumbing. You focus on RL! โœจ


---

## Part 3: Setup ๐Ÿ› ๏ธ

**Running in Colab?** This cell will clone OpenEnv and install dependencies automatically.

**Running locally?** Make sure you're in the OpenEnv directory.

```python

# Detect environment

try:

    import google.colab

    IN_COLAB = True

    print("๐ŸŒ Running in Google Colab - Perfect!")

except ImportError:

    IN_COLAB = False

    print("๐Ÿ’ป Running locally - Nice!")



if IN_COLAB:

    print("\n๐Ÿ“ฆ Cloning OpenEnv repository...")

    !git clone https://github.com/meta-pytorch/OpenEnv.git > /dev/null 2>&1

    %cd OpenEnv

    

    print("๐Ÿ“š Installing dependencies (this takes ~10 seconds)...")

    !pip install -q fastapi uvicorn requests

    

    import sys

    sys.path.insert(0, './src')

    print("\nโœ… Setup complete! Everything is ready to go! ๐ŸŽ‰")

else:

    import sys

    from pathlib import Path

    sys.path.insert(0, str(Path.cwd().parent / 'src'))

    print("โœ… Using local OpenEnv installation")



print("\n๐Ÿš€ Ready to explore OpenEnv and build amazing things!")

print("๐Ÿ’ก Tip: Run cells top-to-bottom for the best experience.\n")

```

**Output:**
```

๐Ÿ’ป Running locally - Nice!

โœ… Using local OpenEnv installation



๐Ÿš€ Ready to explore OpenEnv and build amazing things!

๐Ÿ’ก Tip: Run cells top-to-bottom for the best experience.

```

---

## Part 4: The OpenEnv Pattern ๐Ÿ—๏ธ

### Every OpenEnv Environment Has 3 Components:

```

src/envs/your_env/

โ”œโ”€โ”€ ๐Ÿ“ models.py          โ† Type-safe contracts

โ”‚                           (Action, Observation, State)

โ”‚

โ”œโ”€โ”€ ๐Ÿ“ฑ client.py          โ† What YOU import

โ”‚                           (HTTPEnvClient implementation)

โ”‚

โ””โ”€โ”€ ๐Ÿ–ฅ๏ธ  server/

    โ”œโ”€โ”€ environment.py    โ† Game/simulation logic

    โ”œโ”€โ”€ app.py            โ† FastAPI server

    โ””โ”€โ”€ Dockerfile        โ† Container definition

```

Let's explore the actual OpenEnv code to see how this works:

```python

# Import OpenEnv's core abstractions

from core.env_server import Environment, Action, Observation, State

from core.http_env_client import HTTPEnvClient



print("="*70)

print("   ๐Ÿงฉ OPENENV CORE ABSTRACTIONS")

print("="*70)



print("""

๐Ÿ–ฅ๏ธ  SERVER SIDE (runs in Docker):



    class Environment(ABC):

        '''Base class for all environment implementations'''

        

        @abstractmethod

        def reset(self) -> Observation:

            '''Start new episode'''

        

        @abstractmethod

        def step(self, action: Action) -> Observation:

            '''Execute action, return observation'''

        

        @property

        def state(self) -> State:

            '''Get episode metadata'''



๐Ÿ“ฑ CLIENT SIDE (your training code):



    class HTTPEnvClient(ABC):

        '''Base class for HTTP clients'''

        

        def reset(self) -> StepResult:

            # HTTP POST /reset

        

        def step(self, action) -> StepResult:

            # HTTP POST /step

        

        def state(self) -> State:

            # HTTP GET /state

""")



print("="*70)

print("\nโœจ Same interface on both sides - communication via HTTP!")

print("๐ŸŽฏ You focus on RL, OpenEnv handles the infrastructure.\n")

```

**Output:**
```

======================================================================

   ๐Ÿงฉ OPENENV CORE ABSTRACTIONS

======================================================================



๐Ÿ–ฅ๏ธ  SERVER SIDE (runs in Docker):



    class Environment(ABC):

        '''Base class for all environment implementations'''

        

        @abstractmethod

        def reset(self) -> Observation:

            '''Start new episode'''

        

        @abstractmethod

        def step(self, action: Action) -> Observation:

            '''Execute action, return observation'''

        

        @property

        def state(self) -> State:

            '''Get episode metadata'''



๐Ÿ“ฑ CLIENT SIDE (your training code):



    class HTTPEnvClient(ABC):

        '''Base class for HTTP clients'''

        

        def reset(self) -> StepResult:

            # HTTP POST /reset

        

        def step(self, action) -> StepResult:

            # HTTP POST /step

        

        def state(self) -> State:

            # HTTP GET /state



======================================================================



โœจ Same interface on both sides - communication via HTTP!

๐ŸŽฏ You focus on RL, OpenEnv handles the infrastructure.

```

---

## Part 5: Example Integration - OpenSpiel ๐ŸŽฎ

### What is OpenSpiel?

**OpenSpiel** is a library from DeepMind with **70+ game environments** for RL research.

### OpenEnv's Integration

We've wrapped **6 OpenSpiel games** following the OpenEnv pattern:

| **๐ŸŽฏ Single-Player** | **๐Ÿ‘ฅ Multi-Player** |
|---------------------|---------------------|
| 1. **Catch** - Catch falling ball | 5. **Tic-Tac-Toe** - Classic 3ร—3 |
| 2. **Cliff Walking** - Navigate grid | 6. **Kuhn Poker** - Imperfect info poker |
| 3. **2048** - Tile puzzle | |
| 4. **Blackjack** - Card game | |

This shows how OpenEnv can wrap **any** existing RL library!

```python

from envs.openspiel_env.client import OpenSpielEnv



print("="*70)

print("   ๐Ÿ”Œ HOW OPENENV WRAPS OPENSPIEL")

print("="*70)



print("""

class OpenSpielEnv(HTTPEnvClient[OpenSpielAction, OpenSpielObservation]):

    

    def _step_payload(self, action: OpenSpielAction) -> dict:

        '''Convert typed action to JSON for HTTP'''

        return {

            "action_id": action.action_id,

            "game_name": action.game_name,

        }

    

    def _parse_result(self, payload: dict) -> StepResult:

        '''Parse HTTP JSON response into typed observation'''

        return StepResult(

            observation=OpenSpielObservation(...),

            reward=payload['reward'],

            done=payload['done']

        )



""")



print("โ”€" * 70)

print("\nโœจ Usage (works for ALL OpenEnv environments):")

print("""

  env = OpenSpielEnv(base_url="http://localhost:8000")

  

  result = env.reset()

  # Returns StepResult[OpenSpielObservation] - Type safe!

  

  result = env.step(OpenSpielAction(action_id=2, game_name="catch"))

  # Type checker knows this is valid!

  

  state = env.state()

  # Returns OpenSpielState

""")



print("โ”€" * 70)

print("\n๐ŸŽฏ This pattern works for ANY environment you want to wrap!\n")

```

**Output:**
```

======================================================================

   ๐Ÿ”Œ HOW OPENENV WRAPS OPENSPIEL

======================================================================



class OpenSpielEnv(HTTPEnvClient[OpenSpielAction, OpenSpielObservation]):

    

    def _step_payload(self, action: OpenSpielAction) -> dict:

        '''Convert typed action to JSON for HTTP'''

        return {

            "action_id": action.action_id,

            "game_name": action.game_name,

        }

    

    def _parse_result(self, payload: dict) -> StepResult:

        '''Parse HTTP JSON response into typed observation'''

        return StepResult(

            observation=OpenSpielObservation(...),

            reward=payload['reward'],

            done=payload['done']

        )





โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€



โœจ Usage (works for ALL OpenEnv environments):



  env = OpenSpielEnv(base_url="http://localhost:8000")

  

  result = env.reset()

  # Returns StepResult[OpenSpielObservation] - Type safe!

  

  result = env.step(OpenSpielAction(action_id=2, game_name="catch"))

  # Type checker knows this is valid!

  

  state = env.state()

  # Returns OpenSpielState



โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€



๐ŸŽฏ This pattern works for ANY environment you want to wrap!

```

### Type-Safe Models

```python

# Import OpenSpiel integration models

from envs.openspiel_env.models import (

    OpenSpielAction,

    OpenSpielObservation,

    OpenSpielState

)

from dataclasses import fields



print("="*70)

print("   ๐ŸŽฎ OPENSPIEL INTEGRATION - TYPE-SAFE MODELS")

print("="*70)



print("\n๐Ÿ“ค OpenSpielAction (what you send):")

print("   " + "โ”€" * 64)

for field in fields(OpenSpielAction):

    print(f"   โ€ข {field.name:20s} : {field.type}")



print("\n๐Ÿ“ฅ OpenSpielObservation (what you receive):")

print("   " + "โ”€" * 64)

for field in fields(OpenSpielObservation):

    print(f"   โ€ข {field.name:20s} : {field.type}")



print("\n๐Ÿ“Š OpenSpielState (episode metadata):")

print("   " + "โ”€" * 64)

for field in fields(OpenSpielState):

    print(f"   โ€ข {field.name:20s} : {field.type}")



print("\n" + "="*70)

print("\n๐Ÿ’ก Type safety means:")

print("   โœ… Your IDE autocompletes these fields")

print("   โœ… Typos are caught before running")

print("   โœ… Refactoring is safe")

print("   โœ… Self-documenting code\n")

```

**Output:**
```

======================================================================

   ๐ŸŽฎ OPENSPIEL INTEGRATION - TYPE-SAFE MODELS

======================================================================



๐Ÿ“ค OpenSpielAction (what you send):

   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

   โ€ข metadata             : typing.Dict[str, typing.Any]

   โ€ข action_id            : int

   โ€ข game_name            : str

   โ€ข game_params          : Dict[str, Any]



๐Ÿ“ฅ OpenSpielObservation (what you receive):

   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

   โ€ข done                 : <class 'bool'>

   โ€ข reward               : typing.Union[bool, int, float, NoneType]

   โ€ข metadata             : typing.Dict[str, typing.Any]

   โ€ข info_state           : List[float]

   โ€ข legal_actions        : List[int]

   โ€ข game_phase           : str

   โ€ข current_player_id    : int

   โ€ข opponent_last_action : Optional[int]



๐Ÿ“Š OpenSpielState (episode metadata):

   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

   โ€ข episode_id           : typing.Optional[str]

   โ€ข step_count           : <class 'int'>

   โ€ข game_name            : str

   โ€ข agent_player         : int

   โ€ข opponent_policy      : str

   โ€ข game_params          : Dict[str, Any]

   โ€ข num_players          : int



======================================================================



๐Ÿ’ก Type safety means:

   โœ… Your IDE autocompletes these fields

   โœ… Typos are caught before running

   โœ… Refactoring is safe

   โœ… Self-documenting code

```

### How the Client Works

The client **inherits from HTTPEnvClient** and implements 3 methods:

1. `_step_payload()` - Convert action โ†’ JSON
2. `_parse_result()` - Parse JSON โ†’ typed observation  
3. `_parse_state()` - Parse JSON โ†’ state

That's it! The base class handles all HTTP communication.

---

## Part 6: Using Real OpenSpiel ๐ŸŽฎ

<div style="text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 15px; margin: 30px 0;">

### Now let's USE a production environment!

We'll play **Catch** using OpenEnv's **OpenSpiel integration** ๐ŸŽฏ

This is a REAL environment running in production at companies!

**Get ready for:**

- ๐Ÿ”Œ Using existing environments (not building)
- ๐Ÿค– Testing policies against real games
- ๐Ÿ“Š Live gameplay visualization
- ๐ŸŽฏ Production-ready patterns

</div>

### The Game: Catch ๐Ÿ”ด๐Ÿ“

```

โฌœ โฌœ ๐Ÿ”ด โฌœ โฌœ

โฌœ โฌœ โฌœ โฌœ โฌœ

โฌœ โฌœ โฌœ โฌœ โฌœ   Ball

โฌœ โฌœ โฌœ โฌœ โฌœ

โฌœ โฌœ โฌœ โฌœ โฌœ   falls

โฌœ โฌœ โฌœ โฌœ โฌœ

โฌœ โฌœ โฌœ โฌœ โฌœ   down

โฌœ โฌœ โฌœ โฌœ โฌœ

โฌœ โฌœ โฌœ โฌœ โฌœ

โฌœ โฌœ ๐Ÿ“ โฌœ โฌœ

     Paddle

```

**Rules:**

- 10ร—5 grid
- Ball falls from random column
- Move paddle left/right to catch it

**Actions:**

- `0` = Move LEFT โฌ…๏ธ
- `1` = STAY ๐Ÿ›‘
- `2` = Move RIGHT โžก๏ธ

**Reward:**

- `+1` if caught ๐ŸŽ‰
- `0` if missed ๐Ÿ˜ข

!!! note "Why Catch?"
    - Simple rules (easy to understand)
    - Fast episodes (~5 steps)
    - Clear success/failure
    - Part of OpenSpiel's 70+ games!

    **๐Ÿ’ก The Big Idea:**

    Instead of building this from scratch, we'll USE OpenEnv's existing OpenSpiel integration. Same interface, but production-ready!


```python

from envs.openspiel_env import OpenSpielEnv

from envs.openspiel_env.models import (

    OpenSpielAction,

    OpenSpielObservation,

    OpenSpielState

)

from dataclasses import fields



print("๐ŸŽฎ " + "="*64 + " ๐ŸŽฎ")

print("   โœ… Importing Real OpenSpiel Environment!")

print("๐ŸŽฎ " + "="*64 + " ๐ŸŽฎ\n")



print("๐Ÿ“ฆ What we just imported:")

print("   โ€ข OpenSpielEnv - HTTP client for OpenSpiel games")

print("   โ€ข OpenSpielAction - Type-safe actions")

print("   โ€ข OpenSpielObservation - Type-safe observations")

print("   โ€ข OpenSpielState - Episode metadata\n")



print("๐Ÿ“‹ OpenSpielObservation fields:")

print("   " + "โ”€" * 60)

for field in fields(OpenSpielObservation):

    print(f"   โ€ข {field.name:25s} : {field.type}")



print("\n" + "="*70)

print("\n๐Ÿ’ก This is REAL OpenEnv code - used in production!")

print("   โ€ข Wraps 6 OpenSpiel games (Catch, Tic-Tac-Toe, Poker, etc.)")

print("   โ€ข Type-safe actions and observations")

print("   โ€ข Works via HTTP (we'll see that next!)\n")

```

**Output:**
```

๐ŸŽฎ ================================================================ ๐ŸŽฎ

   โœ… Importing Real OpenSpiel Environment!

๐ŸŽฎ ================================================================ ๐ŸŽฎ



๐Ÿ“ฆ What we just imported:

   โ€ข OpenSpielEnv - HTTP client for OpenSpiel games

   โ€ข OpenSpielAction - Type-safe actions

   โ€ข OpenSpielObservation - Type-safe observations

   โ€ข OpenSpielState - Episode metadata



๐Ÿ“‹ OpenSpielObservation fields:

   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

   โ€ข done                      : <class 'bool'>

   โ€ข reward                    : typing.Union[bool, int, float, NoneType]

   โ€ข metadata                  : typing.Dict[str, typing.Any]

   โ€ข info_state                : List[float]

   โ€ข legal_actions             : List[int]

   โ€ข game_phase                : str

   โ€ข current_player_id         : int

   โ€ข opponent_last_action      : Optional[int]



======================================================================



๐Ÿ’ก This is REAL OpenEnv code - used in production!

   โ€ข Wraps 6 OpenSpiel games (Catch, Tic-Tac-Toe, Poker, etc.)

   โ€ข Type-safe actions and observations

   โ€ข Works via HTTP (we'll see that next!)

```

---

## Part 7: Four Policies ๐Ÿค–

Let's test 4 different AI strategies:

| Policy | Strategy | Expected Performance |
|--------|----------|----------------------|
| **๐ŸŽฒ Random** | Pick random action every step | ~20% (pure luck) |
| **๐Ÿ›‘ Always Stay** | Never move, hope ball lands in center | ~20% (terrible!) |
| **๐Ÿง  Smart** | Move paddle toward ball | 100% (optimal!) |
| **๐Ÿ“ˆ Learning** | Start random, learn smart strategy | ~85% (improves over time) |

**๐Ÿ’ก These policies work with ANY OpenSpiel game!**

```python

import random



# ============================================================================

# POLICIES - Different AI strategies (adapted for OpenSpiel)

# ============================================================================



class RandomPolicy:

    """Baseline: Pure random guessing."""

    name = "๐ŸŽฒ Random Guesser"



    def select_action(self, obs: OpenSpielObservation) -> int:

        return random.choice(obs.legal_actions)





class AlwaysStayPolicy:

    """Bad strategy: Never moves."""

    name = "๐Ÿ›‘ Always Stay"



    def select_action(self, obs: OpenSpielObservation) -> int:

        return 1  # STAY





class SmartPolicy:

    """Optimal: Move paddle toward ball."""

    name = "๐Ÿง  Smart Heuristic"



    def select_action(self, obs: OpenSpielObservation) -> int:

        # Parse OpenSpiel observation

        # For Catch: info_state is a flattened 10x5 grid

        # Ball position and paddle position encoded in the vector

        info_state = obs.info_state



        # Find ball and paddle positions from info_state

        # Catch uses a 10x5 grid, so 50 values

        grid_size = 5



        # Find positions (ball = 1.0 in the flattened grid, paddle = 1.0 in the last row of the flattened grid)

        ball_col = None

        paddle_col = None



        for idx, val in enumerate(info_state):

            if abs(val - 1.0) < 0.01:  # Ball

                ball_col = idx % grid_size

                break



        last_row = info_state[-grid_size:]

        paddle_col = last_row.index(1.0) # Paddle



        if ball_col is not None and paddle_col is not None:

            if paddle_col < ball_col:

                return 2  # Move RIGHT

            elif paddle_col > ball_col:

                return 0  # Move LEFT



        return 1  # STAY (fallback)





class LearningPolicy:

    """Simulated RL: Epsilon-greedy exploration."""

    name = "๐Ÿ“ˆ Learning Agent"



    def __init__(self):

        self.steps = 0

        self.smart_policy = SmartPolicy()



    def select_action(self, obs: OpenSpielObservation) -> int:

        self.steps += 1



        # Decay exploration rate over time

        epsilon = max(0.1, 1.0 - (self.steps / 100))



        if random.random() < epsilon:

            # Explore: random action

            return random.choice(obs.legal_actions)

        else:

            # Exploit: use smart strategy

            return self.smart_policy.select_action(obs)





print("๐Ÿค– " + "="*64 + " ๐Ÿค–")

print("   โœ… 4 Policies Created (Adapted for OpenSpiel)!")

print("๐Ÿค– " + "="*64 + " ๐Ÿค–\n")



policies = [RandomPolicy(), AlwaysStayPolicy(), SmartPolicy(), LearningPolicy()]

for i, policy in enumerate(policies, 1):

    print(f"   {i}. {policy.name}")



print("\n๐Ÿ’ก These policies work with OpenSpielObservation!")

print("   โ€ข Read info_state (flattened grid)")

print("   โ€ข Use legal_actions")

print("   โ€ข Work with ANY OpenSpiel game that exposes these!\n")

```

**Output:**
```

๐Ÿค– ================================================================ ๐Ÿค–

   โœ… 4 Policies Created (Adapted for OpenSpiel)!

๐Ÿค– ================================================================ ๐Ÿค–



   1. ๐ŸŽฒ Random Guesser

   2. ๐Ÿ›‘ Always Stay

   3. ๐Ÿง  Smart Heuristic

   4. ๐Ÿ“ˆ Learning Agent



๐Ÿ’ก These policies work with OpenSpielObservation!

   โ€ข Read info_state (flattened grid)

   โ€ข Use legal_actions

   โ€ข Work with ANY OpenSpiel game that exposes these!

```

---

## Part 8: Policy Competition! ๐Ÿ†

Let's run **50 episodes** for each policy against **REAL OpenSpiel** and see who wins!

This is production code - every action is an HTTP call to the OpenSpiel server!

```python

def evaluate_policies(env, num_episodes=50):

    """Compare all policies over many episodes using real OpenSpiel."""

    policies = [

        RandomPolicy(),

        AlwaysStayPolicy(),

        SmartPolicy(),

        LearningPolicy(),

    ]



    print("\n๐Ÿ† " + "="*66 + " ๐Ÿ†")

    print(f"   POLICY SHOWDOWN - {num_episodes} Episodes Each")

    print(f"   Playing against REAL OpenSpiel Catch!")

    print("๐Ÿ† " + "="*66 + " ๐Ÿ†\n")



    results = []

    for policy in policies:

        print(f"โšก Testing {policy.name}...", end=" ")

        successes = sum(run_episode(env, policy, visualize=False)

                       for _ in range(num_episodes))

        success_rate = (successes / num_episodes) * 100

        results.append((policy.name, success_rate, successes))

        print(f"โœ“ Done!")



    print("\n" + "="*70)

    print("   ๐Ÿ“Š FINAL RESULTS")

    print("="*70 + "\n")



    # Sort by success rate (descending)

    results.sort(key=lambda x: x[1], reverse=True)



    # Award medals to top 3

    medals = ["๐Ÿฅ‡", "๐Ÿฅˆ", "๐Ÿฅ‰", "  "]



    for i, (name, rate, successes) in enumerate(results):

        medal = medals[i]

        bar = "โ–ˆ" * int(rate / 2)

        print(f"{medal} {name:25s} [{bar:<50}] {rate:5.1f}% ({successes}/{num_episodes})")



    print("\n" + "="*70)

    print("\nโœจ Key Insights:")

    print("   โ€ข Random (~20%):      Baseline - pure luck ๐ŸŽฒ")

    print("   โ€ข Always Stay (~20%): Bad strategy - stays center ๐Ÿ›‘")

    print("   โ€ข Smart (100%):       Optimal - perfect play! ๐Ÿง ")

    print("   โ€ข Learning (~85%):    Improves over time ๐Ÿ“ˆ")

    print("\n๐ŸŽ“ This is Reinforcement Learning + OpenEnv in action:")

    print("   1. We USED existing OpenSpiel environment (didn't build it)")

    print("   2. Type-safe communication over HTTP")

    print("   3. Same code works for ANY OpenSpiel game")

    print("   4. Production-ready architecture\n")



# Run the epic competition!

print("๐ŸŽฎ Starting the showdown against REAL OpenSpiel...\n")

evaluate_policies(client, num_episodes=50)

```

---

## Part 9: Switching to Other Games ๐ŸŽฎ

### What We Just Used: Real OpenSpiel! ๐ŸŽ‰

In Parts 6-8, we **USED** the existing OpenSpiel Catch environment:

| What We Did | How It Works |
|-------------|--------------|
| **Imported** | OpenSpielEnv client (pre-built) |
| **Started** | OpenSpiel server via uvicorn |
| **Connected** | HTTP client to server |
| **Played** | Real OpenSpiel Catch game |

**๐ŸŽฏ This is production code!** Every action was an HTTP call to a real OpenSpiel environment.

### ๐ŸŽฎ 6 Games Available - Same Interface!

The beauty of OpenEnv? **Same code, different games!**

```python

# We just used Catch

env = OpenSpielEnv(base_url="http://localhost:8000")

# game_name="catch" was set via environment variable



# Want Tic-Tac-Toe instead? Just change the game!

# Start server with: OPENSPIEL_GAME=tic_tac_toe uvicorn ...

# Same client code works!

```

**๐ŸŽฎ All 6 Games:**

1. โœ… **`catch`** - What we just used!
2. **`tic_tac_toe`** - Classic 3ร—3
3. **`kuhn_poker`** - Imperfect information poker

4. **`cliff_walking`** - Grid navigation
5. **`2048`** - Tile puzzle
6. **`blackjack`** - Card game

**All use the exact same OpenSpielEnv client!**

### Try Another Game (Optional):

```python

# Stop the current server (kill the server_process)

# Then start a new game:



server_process = subprocess.Popen(

    [sys.executable, "-m", "uvicorn",

     "envs.openspiel_env.server.app:app",

     "--host", "0.0.0.0",

     "--port", "8000"],

    env={**os.environ,

         "PYTHONPATH": f"{work_dir}/src",

         "OPENSPIEL_GAME": "tic_tac_toe",  # Changed!

         "OPENSPIEL_AGENT_PLAYER": "0",

         "OPENSPIEL_OPPONENT_POLICY": "random"},

    # ... rest of config

)



# Same client works!

client = OpenSpielEnv(base_url="http://localhost:8000")

result = client.reset()  # Now playing Tic-Tac-Toe!

```

**๐Ÿ’ก Key Insight**: You don't rebuild anything - you just USE different games with the same client!

---

## Part 10: Create Your Own Integration ๐Ÿ› ๏ธ

### The 5-Step Pattern

Want to wrap your own environment in OpenEnv? Here's how:

### Step 1: Define Types (`models.py`)

```python

from dataclasses import dataclass

from core.env_server import Action, Observation, State



@dataclass

class YourAction(Action):

    action_value: int

    # Add your action fields



@dataclass

class YourObservation(Observation):

    state_data: List[float]

    done: bool

    reward: float

    # Add your observation fields



@dataclass

class YourState(State):

    episode_id: str

    step_count: int

    # Add your state fields

```

### Step 2: Implement Environment (`server/environment.py`)

```python

from core.env_server import Environment



class YourEnvironment(Environment):

    def reset(self) -> Observation:

        # Initialize your game/simulation

        return YourObservation(...)

    

    def step(self, action: Action) -> Observation:

        # Execute action, update state

        return YourObservation(...)

    

    @property

    def state(self) -> State:

        return self._state

```

### Step 3: Create Client (`client.py`)

```python

from core.http_env_client import HTTPEnvClient

from core.types import StepResult



class YourEnv(HTTPEnvClient[YourAction, YourObservation]):

    def _step_payload(self, action: YourAction) -> dict:

        """Convert action to JSON"""

        return {"action_value": action.action_value}

    

    def _parse_result(self, payload: dict) -> StepResult:

        """Parse JSON to observation"""

        return StepResult(

            observation=YourObservation(...),

            reward=payload['reward'],

            done=payload['done']

        )

    

    def _parse_state(self, payload: dict) -> YourState:

        return YourState(...)

```

### Step 4: Create Server (`server/app.py`)

```python

from core.env_server import create_fastapi_app

from .your_environment import YourEnvironment



env = YourEnvironment()

app = create_fastapi_app(env)



# That's it! OpenEnv creates all endpoints for you.

```

### Step 5: Dockerize (`server/Dockerfile`)

```dockerfile

FROM python:3.11-slim



WORKDIR /app

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt



COPY . .

CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

```

### ๐ŸŽ“ Examples to Study

OpenEnv includes 3 complete examples:

1. **`src/envs/echo_env/`**

   - Simplest possible environment

   - Great for testing and learning



2. **`src/envs/openspiel_env/`**
   - Wraps external library (OpenSpiel)
   - Shows integration pattern
   - 6 games in one integration

3. **`src/envs/coding_env/`**

   - Python code execution environment

   - Shows complex use case

   - Security considerations



**๐Ÿ’ก Study these to understand the patterns!**



---



## ๐ŸŽ“ Summary: Your Journey



### What You Learned



<table>

<tr>

<td width="50%" style="vertical-align: top;">



### ๐Ÿ“š Concepts



โœ… **RL Fundamentals**



- The observe-act-reward loop

- What makes good policies

- Exploration vs exploitation



โœ… **OpenEnv Architecture**



- Client-server separation

- Type-safe contracts

- HTTP communication layer



โœ… **Production Patterns**



- Docker isolation

- API design

- Reproducible deployments



</td>

<td width="50%" style="vertical-align: top;">



### ๐Ÿ› ๏ธ Skills



โœ… **Using Environments**



- Import OpenEnv clients

- Call reset/step/state

- Work with typed observations



โœ… **Building Environments**



- Define type-safe models

- Implement Environment class

- Create HTTPEnvClient



โœ… **Testing & Debugging**



- Compare policies

- Visualize episodes

- Measure performance



</td>

</tr>

</table>



### OpenEnv vs Traditional RL



| Feature | Traditional (Gym) | OpenEnv | Winner |

|---------|------------------|---------|--------|

| **Type Safety** | โŒ Arrays, dicts | โœ… Dataclasses | ๐Ÿ† OpenEnv |

| **Isolation** | โŒ Same process | โœ… Docker | ๐Ÿ† OpenEnv |

| **Deployment** | โŒ Manual setup | โœ… K8s-ready | ๐Ÿ† OpenEnv |

| **Language** | โŒ Python only | โœ… Any (HTTP) | ๐Ÿ† OpenEnv |

| **Reproducibility** | โŒ "Works on my machine" | โœ… Same everywhere | ๐Ÿ† OpenEnv |

| **Community** | โœ… Large ecosystem | ๐ŸŸก Growing | ๐Ÿค Both! |



!!! success "The Bottom Line"

    OpenEnv brings **production engineering** to RL:

    

    - Same environments work locally and in production

    - Type safety catches bugs early

    - Docker isolation prevents conflicts

    - HTTP API works with any language



    **It's RL for 2024 and beyond.**



---



## ๐Ÿ“š Resources



### ๐Ÿ”— Essential Links



- **๐Ÿ  OpenEnv GitHub**: https://github.com/meta-pytorch/OpenEnv

- **๐ŸŽฎ OpenSpiel**: https://github.com/google-deepmind/open_spiel

- **โšก FastAPI Docs**: https://fastapi.tiangolo.com/

- **๐Ÿณ Docker Guide**: https://docs.docker.com/get-started/

- **๐Ÿ”ฅ PyTorch**: https://pytorch.org/



### ๐Ÿ“– Documentation Deep Dives



- **Environment Creation Guide**: `src/envs/README.md`

- **OpenSpiel Integration**: `src/envs/openspiel_env/README.md`

- **Example Scripts**: `examples/`

- **RFC 001**: [Baseline API Specs](https://github.com/meta-pytorch/OpenEnv/pull/26)



### ๐ŸŽ“ Community & Support



**Supported by amazing organizations:**



- ๐Ÿ”ฅ Meta PyTorch

- ๐Ÿค— Hugging Face

- โšก Unsloth AI

- ๐ŸŒŸ Reflection AI

- ๐Ÿš€ And many more!



**License**: BSD 3-Clause (very permissive!)



**Contributions**: Always welcome! Check out the issues tab.



---



### ๐ŸŒˆ What's Next?



1. โญ **Star the repo** to show support and stay updated

2. ๐Ÿ”„ **Try modifying** the Catch game (make it harder? bigger grid?)

3. ๐ŸŽฎ **Explore** other OpenSpiel games

4. ๐Ÿ› ๏ธ **Build** your own environment integration

5. ๐Ÿ’ฌ **Share** what you build with the community!