File size: 69,556 Bytes
e5f64b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div align=\"center\">\n",
    "\n",
    "<img src=\"https://upload.wikimedia.org/wikipedia/commons/1/10/PyTorch_logo_icon.svg\" width=\"200\" alt=\"PyTorch\">\n",
    "\n",
    "\n",
    "\n",
    "# OpenEnv: Production RL Made Simple\n",
    "\n",
    "### *From \"Hello World\" to RL Training in 5 Minutes* โœจ\n",
    "\n",
    "---\n",
    "\n",
    "**What if RL environments were as easy to use as REST APIs?**\n",
    "\n",
    "That's OpenEnv. Type-safe. Isolated. Production-ready. ๐ŸŽฏ\n",
    "\n",
    "[![GitHub](https://img.shields.io/badge/GitHub-meta--pytorch%2FOpenEnv-blue?logo=github)](https://github.com/meta-pytorch/OpenEnv)\n",
    "[![License](https://img.shields.io/badge/License-BSD%203--Clause-green.svg)](https://opensource.org/licenses/BSD-3-Clause)\n",
    "[![PyTorch](https://img.shields.io/badge/PyTorch-EE4C2C?logo=pytorch&logoColor=white)](https://pytorch.org/)\n",
    "\n",
    "Author: [Sanyam Bhutani](http://twitter.com/bhutanisanyam1/)\n",
    "\n",
    "</div>\n",
    "\n",
    "\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Why OpenEnv?\n",
    "\n",
    "Let's take a trip down memory lane:\n",
    "\n",
    "It's 2016, RL is popular. You read some papers, it looks promising. \n",
    "\n",
    "But in real world: Cartpole is the best you can run on a gaming GPU. \n",
    "\n",
    "What do you do beyond Cartpole?\n",
    "\n",
    "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!\n",
    "\n",
    "The problem still remains, how do you take these RL algorithms and take them beyond Cartpole?\n",
    "\n",
    "A huge part of RL is giving your algorithms environment access to learn. \n",
    "\n",
    "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.\n",
    "\n",
    "Focus on experiments, use OpenEnvironments, and build agents that go beyond Cartpole on a single spec.\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## ๐Ÿ“‹ What You'll Learn\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**๐ŸŽฏ Part 1-2: The Fundamentals**\n",
    "- โšก RL in 60 seconds\n",
    "- ๐Ÿค” Why existing solutions fall short\n",
    "- ๐Ÿ’ก The OpenEnv solution\n",
    "\n",
    "</td>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**๐Ÿ—๏ธ Part 3-5: The Architecture**\n",
    "- ๐Ÿ”ง How OpenEnv works\n",
    "- ๐Ÿ” Exploring real code\n",
    "- ๐ŸŽฎ OpenSpiel integration example\n",
    "\n",
    "</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**๐ŸŽฎ Part 6-8: Hands-On Demo**\n",
    "- ๐Ÿ”Œ Use existing OpenSpiel environment\n",
    "- ๐Ÿค– Test 4 different policies\n",
    "- ๐Ÿ‘€ Watch learning happen live\n",
    "\n",
    "</td>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**๐Ÿ”ง Part 9-10: Going Further**\n",
    "- ๐ŸŽฎ Switch to other OpenSpiel games\n",
    "- โœจ Build your own integration\n",
    "- ๐ŸŒ Deploy to production\n",
    "\n",
    "</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "> ๐Ÿ’ก **Pro Tip**: This notebook is designed to run top-to-bottom in Google Colab with zero setup!\n",
    ">\n",
    "> โฑ๏ธ **Time**: ~5 minutes | ๐Ÿ“Š **Difficulty**: Beginner-friendly | ๐ŸŽฏ **Outcome**: Production-ready RL knowledge\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## ๐Ÿ“‘ Table of Contents\n",
    "\n",
    "<div style=\"background-color: rgba(128, 128, 128, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(128, 128, 128, 0.2);\">\n",
    "\n",
    "**Quick Navigation** - Click any section to jump right there! ๐ŸŽฏ\n",
    "\n",
    "### Foundation\n",
    "- [Part 1: RL in 60 Seconds โฑ๏ธ](#part-1)\n",
    "- [Part 2: The Problem with Traditional RL ๐Ÿ˜ค](#part-2)\n",
    "- [Part 3: Setup ๐Ÿ› ๏ธ](#part-3)\n",
    "\n",
    "### Architecture\n",
    "- [Part 4: The OpenEnv Pattern ๐Ÿ—๏ธ](#part-4)\n",
    "- [Part 5: Example Integration - OpenSpiel ๐ŸŽฎ](#part-5)\n",
    "\n",
    "### Hands-On Demo\n",
    "- [Part 6: Interactive Demo ๐ŸŽฎ](#part-6)\n",
    "- [Part 7: Four Policies ๐Ÿค–](#part-7)\n",
    "- [Part 8: Policy Competition! ๐Ÿ†](#part-8)\n",
    "\n",
    "### Advanced\n",
    "- [Part 9: Using Real OpenSpiel ๐ŸŽฎ](#part-9)\n",
    "- [Part 10: Create Your Own Integration ๐Ÿ› ๏ธ](#part-10)\n",
    "\n",
    "### Wrap Up\n",
    "- [Summary: Your Journey ๐ŸŽ“](#summary)\n",
    "- [Resources ๐Ÿ“š](#resources)\n",
    "\n",
    "</div>\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Part 1: RL in 60 Seconds โฑ๏ธ\n",
    "\n",
    "<div style=\"background-color: rgba(128, 128, 128, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(128, 128, 128, 0.2);\">\n",
    "\n",
    "**Reinforcement Learning is simpler than you think.**\n",
    "\n",
    "It's just a loop:\n",
    "\n",
    "```python\n",
    "while not done:\n",
    "    observation = environment.observe()\n",
    "    action = policy.choose(observation)\n",
    "    reward = environment.step(action)\n",
    "    policy.learn(reward)\n",
    "```\n",
    "\n",
    "That's it. That's RL.\n",
    "\n",
    "</div>\n",
    "\n",
    "Let's see it in action:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "๐ŸŽฒ ========================================================== ๐ŸŽฒ\n",
      "   Number Guessing Game - The Simplest RL Example\n",
      "๐ŸŽฒ ========================================================== ๐ŸŽฒ\n",
      "\n",
      "๐ŸŽฏ I'm thinking of a number between 1 and 10...\n",
      "๐Ÿ’ญ You have 3 guesses. Let's see how random guessing works!\n",
      "\n",
      "๐Ÿ’ญ Guess #1: 4 โ†’ โ„๏ธ  Cold! (far)\n",
      "๐Ÿ’ญ Guess #2: 4 โ†’ โ„๏ธ  Cold! (far)\n",
      "๐Ÿ’ญ Guess #3: 3 โ†’ โ„๏ธ  Cold! (far)\n",
      "\n",
      "๐Ÿ’” Out of guesses. The number was 8.\n",
      "\n",
      "==============================================================\n",
      "๐Ÿ’ก This is RL: Observe โ†’ Act โ†’ Reward โ†’ Repeat\n",
      "   But this policy is terrible! It doesn't learn from rewards.\n",
      "==============================================================\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "print(\"๐ŸŽฒ \" + \"=\"*58 + \" ๐ŸŽฒ\")\n",
    "print(\"   Number Guessing Game - The Simplest RL Example\")\n",
    "print(\"๐ŸŽฒ \" + \"=\"*58 + \" ๐ŸŽฒ\")\n",
    "\n",
    "# Environment setup\n",
    "target = random.randint(1, 10)\n",
    "guesses_left = 3\n",
    "\n",
    "print(f\"\\n๐ŸŽฏ I'm thinking of a number between 1 and 10...\")\n",
    "print(f\"๐Ÿ’ญ You have {guesses_left} guesses. Let's see how random guessing works!\\n\")\n",
    "\n",
    "# The RL Loop - Pure random policy (no learning!)\n",
    "while guesses_left > 0:\n",
    "    # Policy: Random guessing (no learning yet!)\n",
    "    guess = random.randint(1, 10)\n",
    "    guesses_left -= 1\n",
    "    \n",
    "    print(f\"๐Ÿ’ญ Guess #{3-guesses_left}: {guess}\", end=\" โ†’ \")\n",
    "    \n",
    "    # Reward signal (but we're not using it!)\n",
    "    if guess == target:\n",
    "        print(\"๐ŸŽ‰ Correct! +10 points\")\n",
    "        break\n",
    "    elif abs(guess - target) <= 2:\n",
    "        print(\"๐Ÿ”ฅ Warm! (close)\")\n",
    "    else:\n",
    "        print(\"โ„๏ธ  Cold! (far)\")\n",
    "else:\n",
    "    print(f\"\\n๐Ÿ’” Out of guesses. The number was {target}.\")\n",
    "\n",
    "print(\"\\n\" + \"=\"*62)\n",
    "print(\"๐Ÿ’ก This is RL: Observe โ†’ Act โ†’ Reward โ†’ Repeat\")\n",
    "print(\"   But this policy is terrible! It doesn't learn from rewards.\")\n",
    "print(\"=\"*62 + \"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<a id=\"part-2\"></a>\n",
    "# Part 2: The Problem with Traditional RL ๐Ÿ˜ค\n",
    "\n",
    "<div style=\"background-color: rgba(248, 205, 16, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(248, 205, 16, 0.1);\">\n",
    "\n",
    "## ๐Ÿค” Why Can't We Just Use OpenAI Gym?\n",
    "\n",
    "Good question! Gym is great for research, but production needs more...\n",
    "\n",
    "</div>\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<th>Challenge</th>\n",
    "<th>Traditional Approach</th>\n",
    "<th>OpenEnv Solution</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Type Safety</b></td>\n",
    "<td>โŒ <code>obs[0][3]</code> - what is this?</td>\n",
    "<td>โœ… <code>obs.info_state</code> - IDE knows!</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Isolation</b></td>\n",
    "<td>โŒ Same process (can crash your training)</td>\n",
    "<td>โœ… Docker containers (fully isolated)</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Deployment</b></td>\n",
    "<td>โŒ \"Works on my machine\" ๐Ÿคท</td>\n",
    "<td>โœ… Same container everywhere ๐Ÿณ</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Scaling</b></td>\n",
    "<td>โŒ Hard to distribute</td>\n",
    "<td>โœ… Deploy to Kubernetes โ˜ธ๏ธ</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Language</b></td>\n",
    "<td>โŒ Python only</td>\n",
    "<td>โœ… Any language (HTTP API) ๐ŸŒ</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Debugging</b></td>\n",
    "<td>โŒ Cryptic numpy errors</td>\n",
    "<td>โœ… Clear type errors ๐Ÿ›</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "<div style=\"background-color: #d4edda; padding: 20px; border-left: 5px solid #28a745; margin: 20px 0;\">\n",
    "\n",
    "## ๐Ÿ’ก The OpenEnv Philosophy\n",
    "\n",
    "**\"RL environments should be like microservices\"**\n",
    "\n",
    "Think of it like this: You don't run your database in the same process as your web server, right? Same principle!\n",
    "\n",
    "- ๐Ÿ”’ **Isolated**: Run in containers (security + stability)\n",
    "- ๐ŸŒ **Standard**: HTTP API, works everywhere\n",
    "- ๐Ÿ“ฆ **Versioned**: Docker images (reproducibility!)\n",
    "- ๐Ÿš€ **Scalable**: Deploy to cloud with one command\n",
    "- ๐Ÿ›ก๏ธ **Type-safe**: Catch bugs before they happen\n",
    "- ๐Ÿ”„ **Portable**: Works on Mac, Linux, Windows, Cloud\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Architecture\n",
    "\n",
    "```\n",
    "โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”\n",
    "โ”‚  YOUR TRAINING CODE                                        โ”‚\n",
    "โ”‚                                                            โ”‚\n",
    "โ”‚  env = OpenSpielEnv(...)        โ† Import the client      โ”‚\n",
    "โ”‚  result = env.reset()           โ† Type-safe!             โ”‚\n",
    "โ”‚  result = env.step(action)      โ† Type-safe!             โ”‚\n",
    "โ”‚                                                            โ”‚\n",
    "โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜\n",
    "                  โ”‚\n",
    "                  โ”‚  HTTP/JSON (Language-Agnostic)\n",
    "                  โ”‚  POST /reset, POST /step, GET /state\n",
    "                  โ”‚\n",
    "โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”\n",
    "โ”‚  DOCKER CONTAINER                                          โ”‚\n",
    "โ”‚                                                            โ”‚\n",
    "โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”         โ”‚\n",
    "โ”‚  โ”‚  FastAPI Server                              โ”‚         โ”‚\n",
    "โ”‚  โ”‚  โ””โ”€ Environment (reset, step, state)         โ”‚         โ”‚\n",
    "โ”‚  โ”‚     โ””โ”€ Your Game/Simulation Logic            โ”‚         โ”‚\n",
    "โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜         โ”‚\n",
    "โ”‚                                                            โ”‚\n",
    "โ”‚  Isolated โ€ข Reproducible โ€ข Secure                          โ”‚\n",
    "โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜\n",
    "```\n",
    "\n",
    "<div style=\"background-color: #e7f3ff; padding: 15px; border-left: 5px solid #0366d6; margin: 20px 0;\">\n",
    "\n",
    "**๐ŸŽฏ Key Insight**: You never see HTTP details - just clean Python methods!\n",
    "\n",
    "```python\n",
    "env.reset()    # Under the hood: HTTP POST to /reset\n",
    "env.step(...)  # Under the hood: HTTP POST to /step\n",
    "env.state()    # Under the hood: HTTP GET to /state\n",
    "```\n",
    "\n",
    "The magic? OpenEnv handles all the plumbing. You focus on RL! โœจ\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Part 3: Setup ๐Ÿ› ๏ธ\n",
    "\n",
    "<div style=\"background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin: 20px 0;\">\n",
    "\n",
    "**Running in Colab?** This cell will clone OpenEnv and install dependencies automatically.\n",
    "\n",
    "**Running locally?** Make sure you're in the OpenEnv directory.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "๐Ÿ’ป Running locally - Nice!\n",
      "โœ… Using local OpenEnv installation\n",
      "\n",
      "๐Ÿš€ Ready to explore OpenEnv and build amazing things!\n",
      "๐Ÿ’ก Tip: Run cells top-to-bottom for the best experience.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Detect environment\n",
    "try:\n",
    "    import google.colab\n",
    "    IN_COLAB = True\n",
    "    print(\"๐ŸŒ Running in Google Colab - Perfect!\")\n",
    "except ImportError:\n",
    "    IN_COLAB = False\n",
    "    print(\"๐Ÿ’ป Running locally - Nice!\")\n",
    "\n",
    "if IN_COLAB:\n",
    "    print(\"\\n๐Ÿ“ฆ Cloning OpenEnv repository...\")\n",
    "    !git clone https://github.com/meta-pytorch/OpenEnv.git > /dev/null 2>&1\n",
    "    %cd OpenEnv\n",
    "    !git checkout c2997e8 > /dev/null 2>&1\n",
    "    \n",
    "    print(\"๐Ÿ“š Installing dependencies (this takes ~10 seconds)...\")\n",
    "    !pip install -q fastapi uvicorn requests fastmcp\n",
    "    \n",
    "    import sys\n",
    "    sys.path.insert(0, './src')\n",
    "    print(\"\\nโœ… Setup complete! Everything is ready to go! ๐ŸŽ‰\")\n",
    "else:\n",
    "    import sys\n",
    "    from pathlib import Path\n",
    "    sys.path.insert(0, str(Path.cwd().parent))\n",
    "    print(\"โœ… Using local OpenEnv installation\")\n",
    "\n",
    "print(\"\\n๐Ÿš€ Ready to explore OpenEnv and build amazing things!\")\n",
    "print(\"๐Ÿ’ก Tip: Run cells top-to-bottom for the best experience.\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<a id=\"part-4\"></a>\n",
    "# Part 4: The OpenEnv Pattern ๐Ÿ—๏ธ\n",
    "\n",
    "<div style=\"background-color: #f0f7ff; padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "## Every OpenEnv Environment Has 3 Components:\n",
    "\n",
    "```\n",
    "envs/your_env/\n",
    "โ”œโ”€โ”€ ๐Ÿ“ models.py          โ† Type-safe contracts\n",
    "โ”‚                           (Action, Observation, State)\n",
    "โ”‚\n",
    "โ”œโ”€โ”€ ๐Ÿ“ฑ client.py          โ† What YOU import\n",
    "โ”‚                           (HTTPEnvClient implementation)\n",
    "โ”‚\n",
    "โ””โ”€โ”€ ๐Ÿ–ฅ๏ธ  server/\n",
    "    โ”œโ”€โ”€ environment.py    โ† Game/simulation logic\n",
    "    โ”œโ”€โ”€ app.py            โ† FastAPI server\n",
    "    โ””โ”€โ”€ Dockerfile        โ† Container definition\n",
    "```\n",
    "\n",
    "</div>\n",
    "\n",
    "Let's explore the actual OpenEnv code to see how this works:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "======================================================================\n",
      "   ๐Ÿงฉ OPENENV CORE ABSTRACTIONS\n",
      "======================================================================\n",
      "\n",
      "๐Ÿ–ฅ๏ธ  SERVER SIDE (runs in Docker):\n",
      "\n",
      "    class Environment(ABC):\n",
      "        '''Base class for all environment implementations'''\n",
      "\n",
      "        @abstractmethod\n",
      "        def reset(self) -> Observation:\n",
      "            '''Start new episode'''\n",
      "\n",
      "        @abstractmethod\n",
      "        def step(self, action: Action) -> Observation:\n",
      "            '''Execute action, return observation'''\n",
      "\n",
      "        @property\n",
      "        def state(self) -> State:\n",
      "            '''Get episode metadata'''\n",
      "\n",
      "๐Ÿ“ฑ CLIENT SIDE (your training code):\n",
      "\n",
      "    class EnvClient(ABC):\n",
      "        '''Base class for HTTP clients'''\n",
      "\n",
      "        def reset(self) -> StepResult:\n",
      "            # HTTP POST /reset\n",
      "\n",
      "        def step(self, action) -> StepResult:\n",
      "            # HTTP POST /step\n",
      "\n",
      "        def state(self) -> State:\n",
      "            # HTTP GET /state\n",
      "\n",
      "======================================================================\n",
      "\n",
      "โœจ Same interface on both sides - communication via HTTP!\n",
      "๐ŸŽฏ You focus on RL, OpenEnv handles the infrastructure.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Import OpenEnv's core abstractions\n",
    "from openenv.core.env_server import Environment, Action, Observation, State\n",
    "from openenv.core.env_client import EnvClient\n",
    "\n",
    "print(\"=\"*70)\n",
    "print(\"   ๐Ÿงฉ OPENENV CORE ABSTRACTIONS\")\n",
    "print(\"=\"*70)\n",
    "\n",
    "print(\"\"\"\n",
    "๐Ÿ–ฅ๏ธ  SERVER SIDE (runs in Docker):\n",
    "\n",
    "    class Environment(ABC):\n",
    "        '''Base class for all environment implementations'''\n",
    "        \n",
    "        @abstractmethod\n",
    "        def reset(self) -> Observation:\n",
    "            '''Start new episode'''\n",
    "        \n",
    "        @abstractmethod\n",
    "        def step(self, action: Action) -> Observation:\n",
    "            '''Execute action, return observation'''\n",
    "        \n",
    "        @property\n",
    "        def state(self) -> State:\n",
    "            '''Get episode metadata'''\n",
    "\n",
    "๐Ÿ“ฑ CLIENT SIDE (your training code):\n",
    "\n",
    "    class EnvClient(ABC):\n",
    "        '''Base class for HTTP clients'''\n",
    "        \n",
    "        def reset(self) -> StepResult:\n",
    "            # HTTP POST /reset\n",
    "        \n",
    "        def step(self, action) -> StepResult:\n",
    "            # HTTP POST /step\n",
    "        \n",
    "        def state(self) -> State:\n",
    "            # HTTP GET /state\n",
    "\"\"\")\n",
    "\n",
    "print(\"=\"*70)\n",
    "print(\"\\nโœจ Same interface on both sides - communication via HTTP!\")\n",
    "print(\"๐ŸŽฏ You focus on RL, OpenEnv handles the infrastructure.\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Part 5: Example Integration - OpenSpiel ๐ŸŽฎ\n",
    "\n",
    "<div style=\"background-color: #fff3e0; padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "## What is OpenSpiel?\n",
    "\n",
    "**OpenSpiel** is a library from DeepMind with **70+ game environments** for RL research.\n",
    "\n",
    "## OpenEnv's Integration\n",
    "\n",
    "We've wrapped **6 OpenSpiel games** following the OpenEnv pattern:\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**๐ŸŽฏ Single-Player**\n",
    "1. **Catch** - Catch falling ball\n",
    "2. **Cliff Walking** - Navigate grid\n",
    "3. **2048** - Tile puzzle\n",
    "4. **Blackjack** - Card game\n",
    "\n",
    "</td>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**๐Ÿ‘ฅ Multi-Player**\n",
    "5. **Tic-Tac-Toe** - Classic 3ร—3\n",
    "6. **Kuhn Poker** - Imperfect info poker\n",
    "\n",
    "</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "This shows how OpenEnv can wrap **any** existing RL library!\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "======================================================================\n",
      "   ๐Ÿ”Œ HOW OPENENV WRAPS OPENSPIEL\n",
      "======================================================================\n",
      "\n",
      "class OpenSpielEnv(HTTPEnvClient[OpenSpielAction, OpenSpielObservation]):\n",
      "\n",
      "    def _step_payload(self, action: OpenSpielAction) -> dict:\n",
      "        '''Convert typed action to JSON for HTTP'''\n",
      "        return {\n",
      "            \"action_id\": action.action_id,\n",
      "            \"game_name\": action.game_name,\n",
      "        }\n",
      "\n",
      "    def _parse_result(self, payload: dict) -> StepResult:\n",
      "        '''Parse HTTP JSON response into typed observation'''\n",
      "        return StepResult(\n",
      "            observation=OpenSpielObservation(...),\n",
      "            reward=payload['reward'],\n",
      "            done=payload['done']\n",
      "        )\n",
      "\n",
      "\n",
      "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n",
      "\n",
      "โœจ Usage (works for ALL OpenEnv environments):\n",
      "\n",
      "  env = OpenSpielEnv(base_url=\"http://localhost:8000\")\n",
      "\n",
      "  result = env.reset()\n",
      "  # Returns StepResult[OpenSpielObservation] - Type safe!\n",
      "\n",
      "  result = env.step(OpenSpielAction(action_id=2, game_name=\"catch\"))\n",
      "  # Type checker knows this is valid!\n",
      "\n",
      "  state = env.state()\n",
      "  # Returns OpenSpielState\n",
      "\n",
      "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n",
      "\n",
      "๐ŸŽฏ This pattern works for ANY environment you want to wrap!\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from envs.openspiel_env.client import OpenSpielEnv\n",
    "\n",
    "print(\"=\"*70)\n",
    "print(\"   ๐Ÿ”Œ HOW OPENENV WRAPS OPENSPIEL\")\n",
    "print(\"=\"*70)\n",
    "\n",
    "print(\"\"\"\n",
    "class OpenSpielEnv(HTTPEnvClient[OpenSpielAction, OpenSpielObservation]):\n",
    "    \n",
    "    def _step_payload(self, action: OpenSpielAction) -> dict:\n",
    "        '''Convert typed action to JSON for HTTP'''\n",
    "        return {\n",
    "            \"action_id\": action.action_id,\n",
    "            \"game_name\": action.game_name,\n",
    "        }\n",
    "    \n",
    "    def _parse_result(self, payload: dict) -> StepResult:\n",
    "        '''Parse HTTP JSON response into typed observation'''\n",
    "        return StepResult(\n",
    "            observation=OpenSpielObservation(...),\n",
    "            reward=payload['reward'],\n",
    "            done=payload['done']\n",
    "        )\n",
    "\n",
    "\"\"\")\n",
    "\n",
    "print(\"โ”€\" * 70)\n",
    "print(\"\\nโœจ Usage (works for ALL OpenEnv environments):\")\n",
    "print(\"\"\"\n",
    "  env = OpenSpielEnv(base_url=\"http://localhost:8000\")\n",
    "  \n",
    "  result = env.reset()\n",
    "  # Returns StepResult[OpenSpielObservation] - Type safe!\n",
    "  \n",
    "  result = env.step(OpenSpielAction(action_id=2, game_name=\"catch\"))\n",
    "  # Type checker knows this is valid!\n",
    "  \n",
    "  state = env.state()\n",
    "  # Returns OpenSpielState\n",
    "\"\"\")\n",
    "\n",
    "print(\"โ”€\" * 70)\n",
    "print(\"\\n๐ŸŽฏ This pattern works for ANY environment you want to wrap!\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "======================================================================\n",
      "   ๐ŸŽฎ OPENSPIEL INTEGRATION - TYPE-SAFE MODELS\n",
      "======================================================================\n",
      "\n",
      "๐Ÿ“ค OpenSpielAction (what you send):\n",
      "   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n",
      "   โ€ข metadata             : typing.Dict[str, typing.Any]\n",
      "   โ€ข action_id            : <class 'int'>\n",
      "   โ€ข game_name            : <class 'str'>\n",
      "   โ€ข game_params          : typing.Dict[str, typing.Any]\n",
      "\n",
      "๐Ÿ“ฅ OpenSpielObservation (what you receive):\n",
      "   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n",
      "   โ€ข done                 : <class 'bool'>\n",
      "   โ€ข reward               : bool | int | float | None\n",
      "   โ€ข metadata             : typing.Dict[str, typing.Any]\n",
      "   โ€ข info_state           : typing.List[float]\n",
      "   โ€ข legal_actions        : typing.List[int]\n",
      "   โ€ข game_phase           : <class 'str'>\n",
      "   โ€ข current_player_id    : <class 'int'>\n",
      "   โ€ข opponent_last_action : typing.Optional[int]\n",
      "\n",
      "๐Ÿ“Š OpenSpielState (episode metadata):\n",
      "   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n",
      "   โ€ข episode_id           : typing.Optional[str]\n",
      "   โ€ข step_count           : <class 'int'>\n",
      "   โ€ข game_name            : <class 'str'>\n",
      "   โ€ข agent_player         : <class 'int'>\n",
      "   โ€ข opponent_policy      : <class 'str'>\n",
      "   โ€ข game_params          : typing.Dict[str, typing.Any]\n",
      "   โ€ข num_players          : <class 'int'>\n",
      "\n",
      "======================================================================\n",
      "\n",
      "๐Ÿ’ก Type safety means:\n",
      "   โœ… Your IDE autocompletes these fields\n",
      "   โœ… Typos are caught before running\n",
      "   โœ… Refactoring is safe\n",
      "   โœ… Self-documenting code\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from envs.openspiel_env.models import (\n",
    "    OpenSpielAction,\n",
    "    OpenSpielObservation,\n",
    "    OpenSpielState\n",
    ")\n",
    "\n",
    "print(\"=\" * 70)\n",
    "print(\"   ๐ŸŽฎ OPENSPIEL INTEGRATION - TYPE-SAFE MODELS\")\n",
    "print(\"=\" * 70)\n",
    "\n",
    "print(\"\\n๐Ÿ“ค OpenSpielAction (what you send):\")\n",
    "print(\"   \" + \"โ”€\" * 64)\n",
    "for name, field in OpenSpielAction.model_fields.items():\n",
    "    print(f\"   โ€ข {name:20s} : {field.annotation}\")\n",
    "\n",
    "print(\"\\n๐Ÿ“ฅ OpenSpielObservation (what you receive):\")\n",
    "print(\"   \" + \"โ”€\" * 64)\n",
    "for name, field in OpenSpielObservation.model_fields.items():\n",
    "    print(f\"   โ€ข {name:20s} : {field.annotation}\")\n",
    "\n",
    "print(\"\\n๐Ÿ“Š OpenSpielState (episode metadata):\")\n",
    "print(\"   \" + \"โ”€\" * 64)\n",
    "for name, field in OpenSpielState.model_fields.items():\n",
    "    print(f\"   โ€ข {name:20s} : {field.annotation}\")\n",
    "\n",
    "print(\"\\n\" + \"=\" * 70)\n",
    "print(\"\\n๐Ÿ’ก Type safety means:\")\n",
    "print(\"   โœ… Your IDE autocompletes these fields\")\n",
    "print(\"   โœ… Typos are caught before running\")\n",
    "print(\"   โœ… Refactoring is safe\")\n",
    "print(\"   โœ… Self-documenting code\\n\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### How the Client Works\n",
    "\n",
    "<div style=\"background-color: rgba(128, 128, 128, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(128, 128, 128, 0.2);\">\n",
    "\n",
    "The client **inherits from HTTPEnvClient** and implements 3 methods:\n",
    "\n",
    "1. `_step_payload()` - Convert action โ†’ JSON\n",
    "2. `_parse_result()` - Parse JSON โ†’ typed observation  \n",
    "3. `_parse_state()` - Parse JSON โ†’ state\n",
    "\n",
    "That's it! The base class handles all HTTP communication.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<div style=\"text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 15px; margin: 30px 0;\">\n",
    "\n",
    "# ๐ŸŽฎ Part 6: Using Real OpenSpiel\n",
    "\n",
    "### Now let's USE a production environment!\n",
    "\n",
    "We'll play **Catch** using OpenEnv's **OpenSpiel integration** ๐ŸŽฏ<br>\n",
    "This is a REAL environment running in production at companies!\n",
    "\n",
    "<br>\n",
    "\n",
    "**Get ready for:**\n",
    "- ๐Ÿ”Œ Using existing environments (not building)\n",
    "- ๐Ÿค– Testing policies against real games\n",
    "- ๐Ÿ“Š Live gameplay visualization\n",
    "- ๐ŸŽฏ Production-ready patterns\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Game: Catch ๐Ÿ”ด๐Ÿ“\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<td width=\"40%\" style=\"text-align: center;\">\n",
    "\n",
    "```\n",
    "โฌœ โฌœ ๐Ÿ”ด โฌœ โฌœ\n",
    "โฌœ โฌœ โฌœ โฌœ โฌœ\n",
    "โฌœ โฌœ โฌœ โฌœ โฌœ   Ball\n",
    "โฌœ โฌœ โฌœ โฌœ โฌœ\n",
    "โฌœ โฌœ โฌœ โฌœ โฌœ   falls\n",
    "โฌœ โฌœ โฌœ โฌœ โฌœ\n",
    "โฌœ โฌœ โฌœ โฌœ โฌœ   down\n",
    "โฌœ โฌœ โฌœ โฌœ โฌœ\n",
    "โฌœ โฌœ โฌœ โฌœ โฌœ\n",
    "โฌœ โฌœ ๐Ÿ“ โฌœ โฌœ\n",
    "     Paddle\n",
    "```\n",
    "\n",
    "</td>\n",
    "<td width=\"60%\">\n",
    "\n",
    "**Rules:**\n",
    "- 10ร—5 grid\n",
    "- Ball falls from random column\n",
    "- Move paddle left/right to catch it\n",
    "\n",
    "**Actions:**\n",
    "- `0` = Move LEFT โฌ…๏ธ\n",
    "- `1` = STAY ๐Ÿ›‘\n",
    "- `2` = Move RIGHT โžก๏ธ\n",
    "\n",
    "**Reward:**\n",
    "- `+1` if caught ๐ŸŽ‰\n",
    "- `0` if missed ๐Ÿ˜ข\n",
    "\n",
    "</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "<div style=\"background-color: rgba(128, 128, 128, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(128, 128, 128, 0.2);\">\n",
    "\n",
    "**๐ŸŽฏ Why Catch?**\n",
    "- Simple rules (easy to understand)\n",
    "- Fast episodes (~5 steps)\n",
    "- Clear success/failure\n",
    "- Part of OpenSpiel's 70+ games!\n",
    "\n",
    "**๐Ÿ’ก The Big Idea:**\n",
    "Instead of building this from scratch, we'll USE OpenEnv's existing OpenSpiel integration. Same interface, but production-ready!\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "๐ŸŽฎ ================================================================ ๐ŸŽฎ\n",
      "   โœ… Importing Real OpenSpiel Environment!\n",
      "๐ŸŽฎ ================================================================ ๐ŸŽฎ\n",
      "\n",
      "๐Ÿ“ฆ What we just imported:\n",
      "   โ€ข OpenSpielEnv - HTTP client for OpenSpiel games\n",
      "   โ€ข OpenSpielAction - Type-safe actions\n",
      "   โ€ข OpenSpielObservation - Type-safe observations\n",
      "   โ€ข OpenSpielState - Episode metadata\n",
      "\n",
      "๐Ÿ“‹ OpenSpielObservation fields:\n",
      "   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n",
      "   โ€ข done                      : <class 'bool'>\n",
      "   โ€ข reward                    : bool | int | float | None\n",
      "   โ€ข metadata                  : typing.Dict[str, typing.Any]\n",
      "   โ€ข info_state                : typing.List[float]\n",
      "   โ€ข legal_actions             : typing.List[int]\n",
      "   โ€ข game_phase                : <class 'str'>\n",
      "   โ€ข current_player_id         : <class 'int'>\n",
      "   โ€ข opponent_last_action      : typing.Optional[int]\n",
      "\n",
      "======================================================================\n",
      "\n",
      "๐Ÿ’ก This is REAL OpenEnv code - used in production!\n",
      "   โ€ข Wraps 6 OpenSpiel games (Catch, Tic-Tac-Toe, Poker, etc.)\n",
      "   โ€ข Type-safe actions and observations\n",
      "   โ€ข Works via HTTP (we'll see that next!)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from envs.openspiel_env import OpenSpielEnv\n",
    "from envs.openspiel_env.models import (\n",
    "    OpenSpielAction,\n",
    "    OpenSpielObservation,\n",
    "    OpenSpielState,\n",
    ")\n",
    "\n",
    "print(\"๐ŸŽฎ \" + \"=\" * 64 + \" ๐ŸŽฎ\")\n",
    "print(\"   โœ… Importing Real OpenSpiel Environment!\")\n",
    "print(\"๐ŸŽฎ \" + \"=\" * 64 + \" ๐ŸŽฎ\\n\")\n",
    "\n",
    "print(\"๐Ÿ“ฆ What we just imported:\")\n",
    "print(\"   โ€ข OpenSpielEnv - HTTP client for OpenSpiel games\")\n",
    "print(\"   โ€ข OpenSpielAction - Type-safe actions\")\n",
    "print(\"   โ€ข OpenSpielObservation - Type-safe observations\")\n",
    "print(\"   โ€ข OpenSpielState - Episode metadata\\n\")\n",
    "\n",
    "print(\"๐Ÿ“‹ OpenSpielObservation fields:\")\n",
    "print(\"   \" + \"โ”€\" * 60)\n",
    "for name, field in OpenSpielObservation.model_fields.items():\n",
    "    print(f\"   โ€ข {name:25s} : {field.annotation}\")\n",
    "\n",
    "print(\"\\n\" + \"=\" * 70)\n",
    "print(\"\\n๐Ÿ’ก This is REAL OpenEnv code - used in production!\")\n",
    "print(\"   โ€ข Wraps 6 OpenSpiel games (Catch, Tic-Tac-Toe, Poker, etc.)\")\n",
    "print(\"   โ€ข Type-safe actions and observations\")\n",
    "print(\"   โ€ข Works via HTTP (we'll see that next!)\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "๐Ÿš€ ================================================================ ๐Ÿš€\n",
      "   Starting OpenSpiel Server (Catch Game)\n",
      "๐Ÿš€ ================================================================ ๐Ÿš€\n",
      "\n",
      "โœ… OpenSpiel is installed!\n",
      "\n",
      "โšก Starting FastAPI server for OpenSpiel Catch...\n",
      "   (This uses REAL OpenEnv + OpenSpiel integration)\n",
      "\n",
      "โณ Waiting for server to start...\n",
      "\n",
      "โœ… OpenSpiel server is running!\n",
      "๐ŸŒ Server URL: http://localhost:8000\n",
      "๐Ÿ“ Endpoints available:\n",
      "   โ€ข POST /reset\n",
      "   โ€ข POST /step\n",
      "   โ€ข GET /state\n",
      "\n",
      "๐ŸŽฏ This is REAL OpenEnv + OpenSpiel in action!\n",
      "   โ€ข Running actual OpenSpiel Catch game\n",
      "   โ€ข Exposed via FastAPI HTTP server\n",
      "   โ€ข Using OpenEnv's standard interface\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import subprocess\n",
    "import time\n",
    "import sys\n",
    "import os\n",
    "\n",
    "print(\"๐Ÿš€ \" + \"=\"*64 + \" ๐Ÿš€\")\n",
    "print(\"   Starting OpenSpiel Server (Catch Game)\")\n",
    "print(\"๐Ÿš€ \" + \"=\"*64 + \" ๐Ÿš€\\n\")\n",
    "\n",
    "# Check if open_spiel is installed\n",
    "try:\n",
    "    import pyspiel\n",
    "    print(\"โœ… OpenSpiel is installed!\\n\")\n",
    "except ImportError:\n",
    "    print(\"โš ๏ธ  OpenSpiel not found. Installing...\")\n",
    "    import subprocess\n",
    "    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"open_spiel\"])\n",
    "    print(\"โœ… OpenSpiel installed!\\n\")\n",
    "\n",
    "# Start the OpenSpiel server in background\n",
    "print(\"โšก Starting FastAPI server for OpenSpiel Catch...\")\n",
    "print(\"   (This uses REAL OpenEnv + OpenSpiel integration)\\n\")\n",
    "\n",
    "# Determine the correct path\n",
    "if IN_COLAB:\n",
    "    work_dir = \"/content/OpenEnv\"\n",
    "else:\n",
    "    from pathlib import Path\n",
    "    work_dir = str(Path.cwd().parent.absolute())\n",
    "\n",
    "server_process = subprocess.Popen(\n",
    "    [sys.executable, \"-m\", \"uvicorn\",\n",
    "     \"envs.openspiel_env.server.app:app\",\n",
    "     \"--host\", \"0.0.0.0\",\n",
    "     \"--port\", \"8000\"],\n",
    "    env={**os.environ,\n",
    "         \"PYTHONPATH\": f\"{work_dir}/src\",\n",
    "         \"OPENSPIEL_GAME\": \"catch\",\n",
    "         \"OPENSPIEL_AGENT_PLAYER\": \"0\",\n",
    "         \"OPENSPIEL_OPPONENT_POLICY\": \"random\"},\n",
    "    stdout=subprocess.DEVNULL,\n",
    "    stderr=subprocess.DEVNULL,\n",
    "    text=True,\n",
    "    cwd=work_dir\n",
    ")\n",
    "\n",
    "# Wait for server to start\n",
    "print(\"โณ Waiting for server to start...\")\n",
    "time.sleep(5)\n",
    "\n",
    "# Check if server is running\n",
    "import requests\n",
    "try:\n",
    "    response = requests.get('http://localhost:8000/health', timeout=2)\n",
    "    print(\"\\nโœ… OpenSpiel server is running!\")\n",
    "    print(\"๐ŸŒ Server URL: http://localhost:8000\")\n",
    "    print(\"๐Ÿ“ Endpoints available:\")\n",
    "    print(\"   โ€ข POST /reset\")\n",
    "    print(\"   โ€ข POST /step\")\n",
    "    print(\"   โ€ข GET /state\")\n",
    "    print(\"\\n๐ŸŽฏ This is REAL OpenEnv + OpenSpiel in action!\")\n",
    "    print(\"   โ€ข Running actual OpenSpiel Catch game\")\n",
    "    print(\"   โ€ข Exposed via FastAPI HTTP server\")\n",
    "    print(\"   โ€ข Using OpenEnv's standard interface\\n\")\n",
    "except Exception as e:\n",
    "    print(f\"\\nโŒ Server failed to start: {e}\")\n",
    "    print(\"\\n๐Ÿ“‹ Checking error output...\")\n",
    "    server_process.poll()\n",
    "    if server_process.stderr:\n",
    "        stderr = server_process.stderr.read()\n",
    "        if stderr:\n",
    "            print(stderr)\n",
    "    print(\"\\n๐Ÿ’ก Make sure open_spiel is installed:\")\n",
    "    print(\"   pip install open_spiel\")\n",
    "    raise"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "๐Ÿ“ฑ ================================================================ ๐Ÿ“ฑ\n",
      "   Connecting to OpenSpiel Server via HTTP\n",
      "๐Ÿ“ฑ ================================================================ ๐Ÿ“ฑ\n",
      "\n",
      "โœ… Client created!\n",
      "\n",
      "๐Ÿ’ก What just happened:\n",
      "   โ€ข OpenSpielEnv is an HTTPEnvClient subclass\n",
      "   โ€ข It knows how to talk to OpenSpiel servers\n",
      "   โ€ข All communication is type-safe and over HTTP\n",
      "   โ€ข Same client works for ALL OpenSpiel games!\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"๐Ÿ“ฑ \" + \"=\"*64 + \" ๐Ÿ“ฑ\")\n",
    "print(\"   Connecting to OpenSpiel Server via HTTP\")\n",
    "print(\"๐Ÿ“ฑ \" + \"=\"*64 + \" ๐Ÿ“ฑ\\n\")\n",
    "\n",
    "# Create HTTP client for OpenSpiel\n",
    "client = OpenSpielEnv(base_url=\"http://localhost:8000\")\n",
    "\n",
    "print(\"โœ… Client created!\")\n",
    "print(\"\\n๐Ÿ’ก What just happened:\")\n",
    "print(\"   โ€ข OpenSpielEnv is an HTTPEnvClient subclass\")\n",
    "print(\"   โ€ข It knows how to talk to OpenSpiel servers\")\n",
    "print(\"   โ€ข All communication is type-safe and over HTTP\")\n",
    "print(\"   โ€ข Same client works for ALL OpenSpiel games!\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "๐ŸŽฎ ================================================================ ๐ŸŽฎ\n",
      "   Testing Connection - Playing One Step\n",
      "๐ŸŽฎ ================================================================ ๐ŸŽฎ\n",
      "\n",
      "๐Ÿ“ค Calling client.reset()...\n",
      "   Under the hood: HTTP POST to http://localhost:8000/reset\n",
      "\n",
      "๐Ÿ“ฅ Received OpenSpielObservation:\n",
      "   โ€ข info_state: [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]... (first 10 values)\n",
      "   โ€ข number of info_state: 50\n",
      "   โ€ข legal_actions: [0, 1, 2]\n",
      "   โ€ข game_phase: initial\n",
      "   โ€ข done: False\n",
      "\n",
      "๐Ÿ“ค Calling client.step(OpenSpielAction(action_id=1, game_name='catch'))...\n",
      "   Under the hood: HTTP POST to http://localhost:8000/step\n",
      "\n",
      "๐Ÿ“ฅ Received response:\n",
      "   โ€ข Reward: 0.0\n",
      "   โ€ข Done: False\n",
      "   โ€ข legal_actions: [0, 1, 2]\n",
      "\n",
      "๐Ÿ“Š Episode state:\n",
      "   โ€ข episode_id: aec2e599-5633-45d6-a7a3-30f46e8796ab\n",
      "   โ€ข step_count: 1\n",
      "   โ€ข game_name: catch\n",
      "\n",
      "======================================================================\n",
      "\n",
      "๐ŸŽ‰ IT WORKS! We're using REAL OpenSpiel via HTTP!\n",
      "   โœ… Type-safe communication\n",
      "   โœ… Same interface as any OpenEnv environment\n",
      "   โœ… Production-ready architecture\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"๐ŸŽฎ \" + \"=\"*64 + \" ๐ŸŽฎ\")\n",
    "print(\"   Testing Connection - Playing One Step\")\n",
    "print(\"๐ŸŽฎ \" + \"=\"*64 + \" ๐ŸŽฎ\\n\")\n",
    "\n",
    "# Reset the environment (HTTP POST /reset)\n",
    "print(\"๐Ÿ“ค Calling client.reset()...\")\n",
    "print(\"   Under the hood: HTTP POST to http://localhost:8000/reset\\n\")\n",
    "\n",
    "result = client.reset()\n",
    "\n",
    "print(\"๐Ÿ“ฅ Received OpenSpielObservation:\")\n",
    "print(f\"   โ€ข info_state: {result.observation.info_state[:10]}... (first 10 values)\")\n",
    "print(f\"   โ€ข number of info_state: {len(result.observation.info_state)}\")\n",
    "print(f\"   โ€ข legal_actions: {result.observation.legal_actions}\")\n",
    "print(f\"   โ€ข game_phase: {result.observation.game_phase}\")\n",
    "print(f\"   โ€ข done: {result.done}\")\n",
    "\n",
    "# Take an action (HTTP POST /step)\n",
    "print(\"\\n๐Ÿ“ค Calling client.step(OpenSpielAction(action_id=1, game_name=\\'catch\\'))...\")\n",
    "print(\"   Under the hood: HTTP POST to http://localhost:8000/step\\n\")\n",
    "\n",
    "action = OpenSpielAction(action_id=1, game_name=\"catch\")  # STAY\n",
    "result = client.step(action)\n",
    "\n",
    "print(\"๐Ÿ“ฅ Received response:\")\n",
    "print(f\"   โ€ข Reward: {result.reward}\")\n",
    "print(f\"   โ€ข Done: {result.done}\")\n",
    "print(f\"   โ€ข legal_actions: {result.observation.legal_actions}\")\n",
    "\n",
    "# Get state (HTTP GET /state)\n",
    "state = client.state()\n",
    "print(f\"\\n๐Ÿ“Š Episode state:\")\n",
    "print(f\"   โ€ข episode_id: {state.episode_id}\")\n",
    "print(f\"   โ€ข step_count: {state.step_count}\")\n",
    "print(f\"   โ€ข game_name: {state.game_name}\")\n",
    "\n",
    "print(\"\\n\" + \"=\"*70)\n",
    "print(\"\\n๐ŸŽ‰ IT WORKS! We\\'re using REAL OpenSpiel via HTTP!\")\n",
    "print(\"   โœ… Type-safe communication\")\n",
    "print(\"   โœ… Same interface as any OpenEnv environment\")\n",
    "print(\"   โœ… Production-ready architecture\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Part 7: Four Policies ๐Ÿค–\n",
    "\n",
    "<div style=\"background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "## Let's test 4 different AI strategies:\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<th width=\"25%\">Policy</th>\n",
    "<th width=\"50%\">Strategy</th>\n",
    "<th width=\"25%\">Expected Performance</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>๐ŸŽฒ Random</b></td>\n",
    "<td>Pick random action every step</td>\n",
    "<td>~20% (pure luck)</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>๐Ÿ›‘ Always Stay</b></td>\n",
    "<td>Never move, hope ball lands in center</td>\n",
    "<td>~20% (terrible!)</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>๐Ÿง  Smart</b></td>\n",
    "<td>Move paddle toward ball</td>\n",
    "<td>100% (optimal!)</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>๐Ÿ“ˆ Learning</b></td>\n",
    "<td>Start random, learn smart strategy</td>\n",
    "<td>~85% (improves over time)</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "**๐Ÿ’ก These policies work with ANY OpenSpiel game!**\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "# ============================================================================\n",
    "# POLICIES - Different AI strategies (adapted for OpenSpiel)\n",
    "# ============================================================================\n",
    "\n",
    "class RandomPolicy:\n",
    "    \"\"\"Baseline: Pure random guessing.\"\"\"\n",
    "    name = \"๐ŸŽฒ Random Guesser\"\n",
    "\n",
    "    def select_action(self, obs: OpenSpielObservation) -> int:\n",
    "        return random.choice(obs.legal_actions)\n",
    "\n",
    "\n",
    "class AlwaysStayPolicy:\n",
    "    \"\"\"Bad strategy: Never moves.\"\"\"\n",
    "    name = \"๐Ÿ›‘ Always Stay\"\n",
    "\n",
    "    def select_action(self, obs: OpenSpielObservation) -> int:\n",
    "        return 1  # STAY\n",
    "\n",
    "\n",
    "class SmartPolicy:\n",
    "    \"\"\"Optimal: Move paddle toward ball.\"\"\"\n",
    "    name = \"๐Ÿง  Smart Heuristic\"\n",
    "\n",
    "    def select_action(self, obs: OpenSpielObservation) -> int:\n",
    "        # Parse OpenSpiel observation\n",
    "        # For Catch: info_state is a flattened 10x5 grid\n",
    "        # Ball position and paddle position encoded in the vector\n",
    "        info_state = obs.info_state\n",
    "\n",
    "        # Find ball and paddle positions from info_state\n",
    "        # Catch uses a 10x5 grid, so 50 values\n",
    "        grid_size = 5\n",
    "\n",
    "        # Find positions (ball = 1.0 in the flattened grid, paddle = 1.0 in the last row of the flattened grid)\n",
    "        ball_col = None\n",
    "        paddle_col = None\n",
    "\n",
    "        for idx, val in enumerate(info_state):\n",
    "            if abs(val - 1.0) < 0.01:  # Ball\n",
    "                ball_col = idx % grid_size\n",
    "                break\n",
    "\n",
    "        last_row = info_state[-grid_size:]\n",
    "        paddle_col = last_row.index(1.0) # Paddle\n",
    "\n",
    "        if ball_col is not None and paddle_col is not None:\n",
    "            if paddle_col < ball_col:\n",
    "                return 2  # Move RIGHT\n",
    "            elif paddle_col > ball_col:\n",
    "                return 0  # Move LEFT\n",
    "\n",
    "        return 1  # STAY (fallback)\n",
    "\n",
    "\n",
    "class LearningPolicy:\n",
    "    \"\"\"Simulated RL: Epsilon-greedy exploration.\"\"\"\n",
    "    name = \"๐Ÿ“ˆ Learning Agent\"\n",
    "\n",
    "    def __init__(self):\n",
    "        self.steps = 0\n",
    "        self.smart_policy = SmartPolicy()\n",
    "\n",
    "    def select_action(self, obs: OpenSpielObservation) -> int:\n",
    "        self.steps += 1\n",
    "\n",
    "        # Decay exploration rate over time\n",
    "        epsilon = max(0.1, 1.0 - (self.steps / 100))\n",
    "\n",
    "        if random.random() < epsilon:\n",
    "            # Explore: random action\n",
    "            return random.choice(obs.legal_actions)\n",
    "        else:\n",
    "            # Exploit: use smart strategy\n",
    "            return self.smart_policy.select_action(obs)\n",
    "\n",
    "\n",
    "print(\"๐Ÿค– \" + \"=\"*64 + \" ๐Ÿค–\")\n",
    "print(\"   โœ… 4 Policies Created (Adapted for OpenSpiel)!\")\n",
    "print(\"๐Ÿค– \" + \"=\"*64 + \" ๐Ÿค–\\n\")\n",
    "\n",
    "policies = [RandomPolicy(), AlwaysStayPolicy(), SmartPolicy(), LearningPolicy()]\n",
    "for i, policy in enumerate(policies, 1):\n",
    "    print(f\"   {i}. {policy.name}\")\n",
    "\n",
    "print(\"\\n๐Ÿ’ก These policies work with OpenSpielObservation!\")\n",
    "print(\"   โ€ข Read info_state (flattened grid)\")\n",
    "print(\"   โ€ข Use legal_actions\")\n",
    "print(\"   โ€ข Work with ANY OpenSpiel game that exposes these!\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Watch a Policy Play!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "def run_episode(env, policy, visualize=True, delay=0.3):\n",
    "    \"\"\"Run one episode with a policy against OpenSpiel environment.\"\"\"\n",
    "\n",
    "    # RESET\n",
    "    result = env.reset()\n",
    "    obs = result.observation\n",
    "\n",
    "    if visualize:\n",
    "        print(f\"\\n{'='*60}\")\n",
    "        print(f\"   ๐ŸŽฎ {policy.name}\")\n",
    "        print(f\"   ๐ŸŽฒ Playing against OpenSpiel Catch\")\n",
    "        print('='*60 + '\\n')\n",
    "        time.sleep(delay)\n",
    "\n",
    "    total_reward = 0\n",
    "    step = 0\n",
    "    action_names = [\"โฌ…๏ธ  LEFT\", \"๐Ÿ›‘ STAY\", \"โžก๏ธ  RIGHT\"]\n",
    "\n",
    "    # THE RL LOOP\n",
    "    while not obs.done:\n",
    "        # 1. Policy chooses action\n",
    "        action_id = policy.select_action(obs)\n",
    "\n",
    "        # 2. Environment executes (via HTTP!)\n",
    "        action = OpenSpielAction(action_id=action_id, game_name=\"catch\")\n",
    "        result = env.step(action)\n",
    "        obs = result.observation\n",
    "\n",
    "        # 3. Collect reward\n",
    "        if result.reward is not None:\n",
    "            total_reward += result.reward\n",
    "\n",
    "        if visualize:\n",
    "            print(f\"๐Ÿ“ Step {step + 1}: {action_names[action_id]} โ†’ Reward: {result.reward}\")\n",
    "            time.sleep(delay)\n",
    "\n",
    "        step += 1\n",
    "\n",
    "    if visualize:\n",
    "        result_text = \"๐ŸŽ‰ CAUGHT!\" if total_reward > 0 else \"๐Ÿ˜ข MISSED\"\n",
    "        print(f\"\\n{'='*60}\")\n",
    "        print(f\"   {result_text} Total Reward: {total_reward}\")\n",
    "        print('='*60)\n",
    "\n",
    "    return total_reward > 0\n",
    "\n",
    "\n",
    "print(\"๐Ÿ“บ \" + \"=\"*64 + \" ๐Ÿ“บ\")\n",
    "print(\"   Watch Smart Policy Play Against OpenSpiel!\")\n",
    "print(\"๐Ÿ“บ \" + \"=\"*64 + \" ๐Ÿ“บ\\n\")\n",
    "\n",
    "# Demo: Watch Smart Policy in action\n",
    "policy = SmartPolicy()\n",
    "run_episode(client, policy, visualize=True, delay=0.5)\n",
    "\n",
    "print(\"\\n๐Ÿ’ก You just watched REAL OpenSpiel Catch being played!\")\n",
    "print(\"   โ€ข Every action was an HTTP call\")\n",
    "print(\"   โ€ข Game logic runs in the server\")\n",
    "print(\"   โ€ข Client only sends actions and receives observations\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Part 8: Policy Competition! ๐Ÿ†\n",
    "\n",
    "<div style=\"background-color: rgba(3, 102, 214, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "Let's run **50 episodes** for each policy against **REAL OpenSpiel** and see who wins!\n",
    "\n",
    "This is production code - every action is an HTTP call to the OpenSpiel server!\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def evaluate_policies(env, num_episodes=50):\n",
    "    \"\"\"Compare all policies over many episodes using real OpenSpiel.\"\"\"\n",
    "    policies = [\n",
    "        RandomPolicy(),\n",
    "        AlwaysStayPolicy(),\n",
    "        SmartPolicy(),\n",
    "        LearningPolicy(),\n",
    "    ]\n",
    "\n",
    "    print(\"\\n๐Ÿ† \" + \"=\"*66 + \" ๐Ÿ†\")\n",
    "    print(f\"   POLICY SHOWDOWN - {num_episodes} Episodes Each\")\n",
    "    print(f\"   Playing against REAL OpenSpiel Catch!\")\n",
    "    print(\"๐Ÿ† \" + \"=\"*66 + \" ๐Ÿ†\\n\")\n",
    "\n",
    "    results = []\n",
    "    for policy in policies:\n",
    "        print(f\"โšก Testing {policy.name}...\", end=\" \")\n",
    "        successes = sum(run_episode(env, policy, visualize=False)\n",
    "                       for _ in range(num_episodes))\n",
    "        success_rate = (successes / num_episodes) * 100\n",
    "        results.append((policy.name, success_rate, successes))\n",
    "        print(f\"โœ“ Done!\")\n",
    "\n",
    "    print(\"\\n\" + \"=\"*70)\n",
    "    print(\"   ๐Ÿ“Š FINAL RESULTS\")\n",
    "    print(\"=\"*70 + \"\\n\")\n",
    "\n",
    "    # Sort by success rate (descending)\n",
    "    results.sort(key=lambda x: x[1], reverse=True)\n",
    "\n",
    "    # Award medals to top 3\n",
    "    medals = [\"๐Ÿฅ‡\", \"๐Ÿฅˆ\", \"๐Ÿฅ‰\", \"  \"]\n",
    "\n",
    "    for i, (name, rate, successes) in enumerate(results):\n",
    "        medal = medals[i]\n",
    "        bar = \"โ–ˆ\" * int(rate / 2)\n",
    "        print(f\"{medal} {name:25s} [{bar:<50}] {rate:5.1f}% ({successes}/{num_episodes})\")\n",
    "\n",
    "    print(\"\\n\" + \"=\"*70)\n",
    "    print(\"\\nโœจ Key Insights:\")\n",
    "    print(\"   โ€ข Random (~20%):      Baseline - pure luck ๐ŸŽฒ\")\n",
    "    print(\"   โ€ข Always Stay (~20%): Bad strategy - stays center ๐Ÿ›‘\")\n",
    "    print(\"   โ€ข Smart (100%):       Optimal - perfect play! ๐Ÿง \")\n",
    "    print(\"   โ€ข Learning (~85%):    Improves over time ๐Ÿ“ˆ\")\n",
    "    print(\"\\n๐ŸŽ“ This is Reinforcement Learning + OpenEnv in action:\")\n",
    "    print(\"   1. We USED existing OpenSpiel environment (didn\\'t build it)\")\n",
    "    print(\"   2. Type-safe communication over HTTP\")\n",
    "    print(\"   3. Same code works for ANY OpenSpiel game\")\n",
    "    print(\"   4. Production-ready architecture\\n\")\n",
    "\n",
    "# Run the epic competition!\n",
    "print(\"๐ŸŽฎ Starting the showdown against REAL OpenSpiel...\\n\")\n",
    "evaluate_policies(client, num_episodes=50)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<a id=\"part-9\"></a>\n",
    "# Part 9: Switching to Other Games ๐ŸŽฎ\n",
    "\n",
    "<div style=\"background-color: rgba(40, 167, 69, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "## What We Just Used: Real OpenSpiel! ๐ŸŽ‰\n",
    "\n",
    "In Parts 6-8, we **USED** the existing OpenSpiel Catch environment:\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<th>What We Did</th>\n",
    "<th>How It Works</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Imported</b></td>\n",
    "<td>OpenSpielEnv client (pre-built)</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Started</b></td>\n",
    "<td>OpenSpiel server via uvicorn</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Connected</b></td>\n",
    "<td>HTTP client to server</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Played</b></td>\n",
    "<td>Real OpenSpiel Catch game</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "**๐ŸŽฏ This is production code!** Every action was an HTTP call to a real OpenSpiel environment.\n",
    "\n",
    "</div>\n",
    "\n",
    "## ๐ŸŽฎ 6 Games Available - Same Interface!\n",
    "\n",
    "The beauty of OpenEnv? **Same code, different games!**\n",
    "\n",
    "```python\n",
    "# We just used Catch\n",
    "env = OpenSpielEnv(base_url=\"http://localhost:8000\")\n",
    "# game_name=\"catch\" was set via environment variable\n",
    "\n",
    "# Want Tic-Tac-Toe instead? Just change the game!\n",
    "# Start server with: OPENSPIEL_GAME=tic_tac_toe uvicorn ...\n",
    "# Same client code works!\n",
    "```\n",
    "\n",
    "<div style=\"background-color: rgba(255, 152, 0, 0.1); padding: 15px; border-radius: 5px; margin: 20px 0;\">\n",
    "\n",
    "**๐ŸŽฎ All 6 Games:**\n",
    "\n",
    "1. โœ… **`catch`** - What we just used!\n",
    "2. **`tic_tac_toe`** - Classic 3ร—3\n",
    "3. **`kuhn_poker`** - Imperfect information poker\n",
    "4. **`cliff_walking`** - Grid navigation\n",
    "5. **`2048`** - Tile puzzle\n",
    "6. **`blackjack`** - Card game\n",
    "\n",
    "**All use the exact same OpenSpielEnv client!**\n",
    "\n",
    "</div>\n",
    "\n",
    "### Try Another Game (Optional):\n",
    "\n",
    "```python\n",
    "# Stop the current server (kill the server_process)\n",
    "# Then start a new game:\n",
    "\n",
    "server_process = subprocess.Popen(\n",
    "    [sys.executable, \"-m\", \"uvicorn\",\n",
    "     \"envs.openspiel_env.server.app:app\",\n",
    "     \"--host\", \"0.0.0.0\",\n",
    "     \"--port\", \"8000\"],\n",
    "    env={**os.environ,\n",
    "         \"PYTHONPATH\": f\"{work_dir}/src\",\n",
    "         \"OPENSPIEL_GAME\": \"tic_tac_toe\",  # Changed!\n",
    "         \"OPENSPIEL_AGENT_PLAYER\": \"0\",\n",
    "         \"OPENSPIEL_OPPONENT_POLICY\": \"random\"},\n",
    "    # ... rest of config\n",
    ")\n",
    "\n",
    "# Same client works!\n",
    "client = OpenSpielEnv(base_url=\"http://localhost:8000\")\n",
    "result = client.reset()  # Now playing Tic-Tac-Toe!\n",
    "```\n",
    "\n",
    "**๐Ÿ’ก Key Insight**: You don't rebuild anything - you just USE different games with the same client!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<a id=\"part-10\"></a>\n",
    "# Part 10: Create Your Own Integration ๐Ÿ› ๏ธ\n",
    "\n",
    "<div style=\"background-color: rgba(3, 102, 214, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "## The 5-Step Pattern\n",
    "\n",
    "Want to wrap your own environment in OpenEnv? Here's how:\n",
    "\n",
    "</div>\n",
    "\n",
    "### Step 1: Define Types (`models.py`)\n",
    "\n",
    "```python\n",
    "from dataclasses import dataclass\n",
    "from openenv.core.env_server import Action, Observation, State\n",
    "\n",
    "@dataclass\n",
    "class YourAction(Action):\n",
    "    action_value: int\n",
    "    # Add your action fields\n",
    "\n",
    "@dataclass\n",
    "class YourObservation(Observation):\n",
    "    state_data: List[float]\n",
    "    done: bool\n",
    "    reward: float\n",
    "    # Add your observation fields\n",
    "\n",
    "@dataclass\n",
    "class YourState(State):\n",
    "    episode_id: str\n",
    "    step_count: int\n",
    "    # Add your state fields\n",
    "```\n",
    "\n",
    "### Step 2: Implement Environment (`server/environment.py`)\n",
    "\n",
    "```python\n",
    "from openenv.core.env_server import Environment\n",
    "\n",
    "class YourEnvironment(Environment):\n",
    "    def reset(self) -> Observation:\n",
    "        # Initialize your game/simulation\n",
    "        return YourObservation(...)\n",
    "    \n",
    "    def step(self, action: Action) -> Observation:\n",
    "        # Execute action, update state\n",
    "        return YourObservation(...)\n",
    "    \n",
    "    @property\n",
    "    def state(self) -> State:\n",
    "        return self._state\n",
    "```\n",
    "\n",
    "### Step 3: Create Client (`client.py`)\n",
    "\n",
    "```python\n",
    "from openenv.core.http_env_client import HTTPEnvClient\n",
    "from openenv.core.types import StepResult\n",
    "\n",
    "class YourEnv(HTTPEnvClient[YourAction, YourObservation]):\n",
    "    def _step_payload(self, action: YourAction) -> dict:\n",
    "        \"\"\"Convert action to JSON\"\"\"\n",
    "        return {\"action_value\": action.action_value}\n",
    "    \n",
    "    def _parse_result(self, payload: dict) -> StepResult:\n",
    "        \"\"\"Parse JSON to observation\"\"\"\n",
    "        return StepResult(\n",
    "            observation=YourObservation(...),\n",
    "            reward=payload['reward'],\n",
    "            done=payload['done']\n",
    "        )\n",
    "    \n",
    "    def _parse_state(self, payload: dict) -> YourState:\n",
    "        return YourState(...)\n",
    "```\n",
    "\n",
    "### Step 4: Create Server (`server/app.py`)\n",
    "\n",
    "```python\n",
    "from openenv.core.env_server import create_fastapi_app\n",
    "from .your_environment import YourEnvironment\n",
    "\n",
    "env = YourEnvironment()\n",
    "app = create_fastapi_app(env)\n",
    "\n",
    "# That's it! OpenEnv creates all endpoints for you.\n",
    "```\n",
    "\n",
    "### Step 5: Dockerize (`server/Dockerfile`)\n",
    "\n",
    "```dockerfile\n",
    "FROM python:3.11-slim\n",
    "\n",
    "WORKDIR /app\n",
    "COPY requirements.txt .\n",
    "RUN pip install --no-cache-dir -r requirements.txt\n",
    "\n",
    "COPY . .\n",
    "CMD [\"uvicorn\", \"app:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n",
    "```\n",
    "\n",
    "<div style=\"background-color: rgba(40, 167, 69, 0.1); padding: 20px; border-left: 5px solid #28a745; margin: 20px 0;\">\n",
    "\n",
    "### ๐ŸŽ“ Examples to Study\n",
    "\n",
    "OpenEnv includes 3 complete examples:\n",
    "\n",
    "1. **`envs/echo_env/`**\n",
    "   - Simplest possible environment\n",
    "   - Great for testing and learning\n",
    "\n",
    "2. **`envs/openspiel_env/`**\n",
    "   - Wraps external library (OpenSpiel)\n",
    "   - Shows integration pattern\n",
    "   - 6 games in one integration\n",
    "\n",
    "3. **`envs/coding_env/`**\n",
    "   - Python code execution environment\n",
    "   - Shows complex use case\n",
    "   - Security considerations\n",
    "\n",
    "**๐Ÿ’ก Study these to understand the patterns!**\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<div style=\"background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px; border-radius: 15px; margin: 40px 0; text-align: center;\">\n",
    "\n",
    "# ๐ŸŽ“ Summary: Your Journey\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What You Learned\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<td width=\"50%\" style=\"vertical-align: top;\">\n",
    "\n",
    "### ๐Ÿ“š Concepts\n",
    "\n",
    "โœ… **RL Fundamentals**\n",
    "- The observe-act-reward loop\n",
    "- What makes good policies\n",
    "- Exploration vs exploitation\n",
    "\n",
    "โœ… **OpenEnv Architecture**\n",
    "- Client-server separation\n",
    "- Type-safe contracts\n",
    "- HTTP communication layer\n",
    "\n",
    "โœ… **Production Patterns**\n",
    "- Docker isolation\n",
    "- API design\n",
    "- Reproducible deployments\n",
    "\n",
    "</td>\n",
    "<td width=\"50%\" style=\"vertical-align: top;\">\n",
    "\n",
    "### ๐Ÿ› ๏ธ Skills\n",
    "\n",
    "โœ… **Using Environments**\n",
    "- Import OpenEnv clients\n",
    "- Call reset/step/state\n",
    "- Work with typed observations\n",
    "\n",
    "โœ… **Building Environments**\n",
    "- Define type-safe models\n",
    "- Implement Environment class\n",
    "- Create HTTPEnvClient\n",
    "\n",
    "โœ… **Testing & Debugging**\n",
    "- Compare policies\n",
    "- Visualize episodes\n",
    "- Measure performance\n",
    "\n",
    "</td>\n",
    "</tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## OpenEnv vs Traditional RL\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<th>Feature</th>\n",
    "<th>Traditional (Gym)</th>\n",
    "<th>OpenEnv</th>\n",
    "<th>Winner</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Type Safety</b></td>\n",
    "<td>โŒ Arrays, dicts</td>\n",
    "<td>โœ… Dataclasses</td>\n",
    "<td>๐Ÿ† OpenEnv</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Isolation</b></td>\n",
    "<td>โŒ Same process</td>\n",
    "<td>โœ… Docker</td>\n",
    "<td>๐Ÿ† OpenEnv</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Deployment</b></td>\n",
    "<td>โŒ Manual setup</td>\n",
    "<td>โœ… K8s-ready</td>\n",
    "<td>๐Ÿ† OpenEnv</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Language</b></td>\n",
    "<td>โŒ Python only</td>\n",
    "<td>โœ… Any (HTTP)</td>\n",
    "<td>๐Ÿ† OpenEnv</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Reproducibility</b></td>\n",
    "<td>โŒ \"Works on my machine\"</td>\n",
    "<td>โœ… Same everywhere</td>\n",
    "<td>๐Ÿ† OpenEnv</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Community</b></td>\n",
    "<td>โœ… Large ecosystem</td>\n",
    "<td>๐ŸŸก Growing</td>\n",
    "<td>๐Ÿค Both!</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "<div style=\"background-color: rgba(3, 102, 214, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "**๐ŸŽฏ The Bottom Line**\n",
    "\n",
    "OpenEnv brings **production engineering** to RL:\n",
    "- Same environments work locally and in production\n",
    "- Type safety catches bugs early\n",
    "- Docker isolation prevents conflicts\n",
    "- HTTP API works with any language\n",
    "\n",
    "**It's RL for 2024 and beyond.**\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"resources\"></a>\n",
    "## ๐Ÿ“š Resources\n",
    "\n",
    "<div style=\"background-color: rgba(128, 128, 128, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(128, 128, 128, 0.2);\">\n",
    "\n",
    "### ๐Ÿ”— Essential Links\n",
    "\n",
    "- **๐Ÿ  OpenEnv GitHub**: https://github.com/meta-pytorch/OpenEnv\n",
    "- **๐ŸŽฎ OpenSpiel**: https://github.com/google-deepmind/open_spiel\n",
    "- **โšก FastAPI Docs**: https://fastapi.tiangolo.com/\n",
    "- **๐Ÿณ Docker Guide**: https://docs.docker.com/get-started/\n",
    "- **๐Ÿ”ฅ PyTorch**: https://pytorch.org/\n",
    "\n",
    "### ๐Ÿ“– Documentation Deep Dives\n",
    "\n",
    "- **Environment Creation Guide**: `envs/README.md`\n",
    "- **OpenSpiel Integration**: `envs/openspiel_env/README.md`\n",
    "- **Example Scripts**: `examples/`\n",
    "- **RFC 001**: [Baseline API Specs](https://github.com/meta-pytorch/OpenEnv/pull/26)\n",
    "\n",
    "### ๐ŸŽ“ Community & Support\n",
    "\n",
    "**Supported by amazing organizations:**\n",
    "- ๐Ÿ”ฅ Meta PyTorch\n",
    "- ๐Ÿค— Hugging Face\n",
    "- โšก Unsloth AI\n",
    "- ๐ŸŒŸ Reflection AI\n",
    "- ๐Ÿš€ And many more!\n",
    "\n",
    "**License**: BSD 3-Clause (very permissive!)\n",
    "\n",
    "**Contributions**: Always welcome! Check out the issues tab.\n",
    "\n",
    "</div>\n",
    "\n",
    "---\n",
    "\n",
    "### ๐ŸŒˆ What's Next?\n",
    "\n",
    "1. โญ **Star the repo** to show support and stay updated\n",
    "2. ๐Ÿ”„ **Try modifying** the Catch game (make it harder? bigger grid?)\n",
    "3. ๐ŸŽฎ **Explore** other OpenSpiel games\n",
    "4. ๐Ÿ› ๏ธ **Build** your own environment integration\n",
    "5. ๐Ÿ’ฌ **Share** what you build with the community!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}