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
 
 
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
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
export interface CookbookRecipe {
  title: string;
  desc: string;
  category: string;
  tags: string[];
  code: string;
}

export const COOKBOOK_CATEGORIES = [
  'All',
  'Agents & Orchestration',
  'Responses API',
  'Evals & Testing',
  'Fine-Tuning & Distillation',
  'Realtime & Voice',
  'Multimodal & Vision',
  'RAG & Search',
  'Embeddings & Clustering',
  'Vector Databases',
  'Codex & Code',
  'MCP & Connectors',
  'Deep Research',
  'Structured Output',
  'Guardrails & Safety',
  'Prompt Engineering',
  'Optimization & Caching',
  'Open Models',
  'Text & NLP',
  'Image & Video Gen',
  'Function Calling',
  'HuggingFace Hub',
] as const;

export const COOKBOOK: CookbookRecipe[] = [
  // ─────────────────────────────────────────────────────
  // AGENTS & ORCHESTRATION  (from OpenAI Cookbook /topic/agents)
  // ─────────────────────────────────────────────────────
  {
    title: 'Build a Governed Agent',
    desc: 'Create a multi-tool agent with a11oy governance, proof chains, and audit trails using Agents SDK.',
    category: 'Agents & Orchestration',
    tags: ['agents-sdk', 'governance', 'proof-chain'],
    code: `from agents import Agent, Runner
from a11oy.governance import ProofChain

triage = Agent(
    name="a11oy-triage",
    instructions="Route user requests to the correct specialist agent. "
                 "Log every routing decision to proof chain.",
    handoffs=["research-agent", "action-agent"],
)

research = Agent(
    name="research-agent",
    instructions="Gather data from connected sources. "
                 "Always cite your sources with timestamps.",
    tools=[web_search, file_search],
)

action = Agent(
    name="action-agent",
    instructions="Execute approved actions. "
                 "Require human-in-the-loop for destructive ops.",
    tools=[send_email, create_ticket],
)

result = Runner.run(triage, "Analyze Q4 revenue trends and draft a summary")
proof = ProofChain.seal(result, signer="a11oy-orchestrator")
print(proof.hash)`,
  },
  {
    title: 'Orchestrating Multi-Agent Pipelines',
    desc: 'Build complex multi-agent workflows with handoffs, guardrails, and parallel execution.',
    category: 'Agents & Orchestration',
    tags: ['multi-agent', 'handoffs', 'pipeline'],
    code: `from agents import Agent, Runner, handoff, GuardrailFunctionOutput
from a11oy.mesh import AgentMesh

def compliance_guardrail(ctx, agent, input_data):
    result = agent.run_sync("Check compliance: " + input_data)
    if "violation" in result.lower():
        return GuardrailFunctionOutput(
            output_info={"violation": True},
            tripwire_triggered=True,
        )
    return GuardrailFunctionOutput(output_info={"violation": False})

analyst = Agent(
    name="financial-analyst",
    instructions="Analyze financial data with precision.",
    output_guardrails=[compliance_guardrail],
)

writer = Agent(
    name="report-writer",
    instructions="Write executive summaries from analyst output.",
    handoff_description="Writes polished reports",
)

orchestrator = Agent(
    name="a11oy-orchestrator",
    instructions="Coordinate analysis and reporting pipeline.",
    handoffs=[handoff(analyst), handoff(writer)],
)

mesh = AgentMesh(orchestrator)
result = await mesh.execute("Generate Q4 earnings analysis")
print(result.final_output)`,
  },
  {
    title: 'Build a Coding Agent with GPT-5.1',
    desc: 'Create an autonomous coding agent that reads, writes, and tests code with sandboxed execution.',
    category: 'Agents & Orchestration',
    tags: ['codex', 'code-agent', 'gpt-5.1'],
    code: `from openai import OpenAI
from a11oy.sandbox import CodeSandbox

client = OpenAI()
sandbox = CodeSandbox(timeout=300)

response = client.responses.create(
    model="gpt-5.1",
    input=[{
        "role": "user",
        "content": "Write a Python function that implements "
                   "a concurrent rate limiter using asyncio. "
                   "Include comprehensive tests."
    }],
    tools=[{
        "type": "code_interpreter",
        "container": {"type": "auto"},
    }],
)

for item in response.output:
    if item.type == "code_interpreter_call":
        result = sandbox.execute(item.code)
        print(f"Exit code: {result.exit_code}")
        print(result.stdout)`,
  },
  {
    title: 'Agent with LangChain Tools',
    desc: 'Build a tool-using agent combining LangChain with a11oy governance layer.',
    category: 'Agents & Orchestration',
    tags: ['langchain', 'tools', 'agent'],
    code: `from langchain.agents import initialize_agent, AgentType
from langchain.tools import Tool
from langchain_openai import ChatOpenAI
from a11oy.governance import AuditLogger

llm = ChatOpenAI(model="gpt-5.1", temperature=0)
audit = AuditLogger(namespace="a11oy.agents")

tools = [
    Tool(name="vessel_lookup", func=lookup_vessel,
         description="Look up vessel details by IMO number"),
    Tool(name="risk_score", func=calculate_risk,
         description="Calculate risk score for an entity"),
    Tool(name="compliance_check", func=check_compliance,
         description="Run compliance check against regulations"),
]

agent = initialize_agent(
    tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True
)

result = agent.run("Check compliance for vessel IMO 9434761")
audit.log(action="compliance_check", result=result)`,
  },
  {
    title: 'Assistants API Overview',
    desc: 'Complete guide to the Assistants API with threads, runs, file search, and code interpreter.',
    category: 'Agents & Orchestration',
    tags: ['assistants', 'threads', 'runs'],
    code: `from openai import OpenAI
client = OpenAI()

assistant = client.beta.assistants.create(
    name="a11oy-research-assistant",
    instructions="You are an expert research analyst for SZL Holdings. "
                 "Use file search for internal docs, code interpreter for analysis.",
    model="gpt-5.1",
    tools=[
        {"type": "file_search"},
        {"type": "code_interpreter"},
    ],
)

thread = client.beta.threads.create()

client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="Analyze our Q4 portfolio risk exposure across all sectors",
)

run = client.beta.threads.runs.create_and_poll(
    thread_id=thread.id,
    assistant_id=assistant.id,
)

if run.status == "completed":
    messages = client.beta.threads.messages.list(thread_id=thread.id)
    for msg in messages.data:
        if msg.role == "assistant":
            print(msg.content[0].text.value)`,
  },
  {
    title: 'ChatGPT Agent for Sales Meeting Prep',
    desc: 'Build a sales prep agent that researches prospects and generates briefings.',
    category: 'Agents & Orchestration',
    tags: ['chatgpt', 'sales', 'meeting-prep'],
    code: `from agents import Agent, Runner, WebSearchTool, FileSearchTool

sales_researcher = Agent(
    name="a11oy-sales-researcher",
    instructions="""Research the prospect company thoroughly:
    1. Recent news and press releases
    2. Financial performance and funding
    3. Key decision makers and their backgrounds
    4. Competitive landscape
    5. Potential pain points a11oy can solve
    Format as a structured briefing document.""",
    tools=[WebSearchTool(), FileSearchTool(
        vector_store_ids=["vs_crm_data"]
    )],
)

briefing = Runner.run(
    sales_researcher,
    "Prepare meeting brief for tomorrow's call with Acme Corp CEO"
)
print(briefing.final_output)`,
  },
  {
    title: 'Multi-Agent Structured Output',
    desc: 'Coordinate multiple agents producing structured JSON outputs with validation.',
    category: 'Agents & Orchestration',
    tags: ['multi-agent', 'structured-output', 'validation'],
    code: `from agents import Agent, Runner
from pydantic import BaseModel
from typing import List

class RiskAssessment(BaseModel):
    entity: str
    risk_level: str
    score: float
    factors: List[str]
    recommendation: str

risk_agent = Agent(
    name="a11oy-risk-assessor",
    instructions="Assess risk for the given entity. "
                 "Consider financial, operational, and regulatory factors.",
    output_type=RiskAssessment,
)

summarizer = Agent(
    name="a11oy-summarizer",
    instructions="Summarize multiple risk assessments into an executive brief.",
    handoffs=[],
)

entities = ["Vessel IMO-9434761", "Port of Rotterdam", "Carrier XYZ"]
assessments = []
for entity in entities:
    result = Runner.run(risk_agent, f"Assess risk for: {entity}")
    assessments.append(result.final_output_as(RiskAssessment))

for a in assessments:
    print(f"{a.entity}: {a.risk_level} ({a.score:.2f})")`,
  },

  // ─────────────────────────────────────────────────────
  // RESPONSES API
  // ─────────────────────────────────────────────────────
  {
    title: 'Responses API Quickstart',
    desc: 'Use the new Responses API with streaming, tools, and structured outputs.',
    category: 'Responses API',
    tags: ['responses', 'streaming', 'tools'],
    code: `from openai import OpenAI
client = OpenAI()

response = client.responses.create(
    model="gpt-5.1",
    input="Analyze the current state of maritime shipping regulations",
    instructions="You are an a11oy governance analyst. "
                 "Provide structured, actionable insights.",
)
print(response.output_text)

stream = client.responses.create(
    model="gpt-5.1",
    input="Stream a detailed risk assessment for Q4 operations",
    stream=True,
)
for event in stream:
    if hasattr(event, 'delta'):
        print(event.delta, end="", flush=True)`,
  },
  {
    title: 'File Search with Responses API',
    desc: 'Search uploaded files and vector stores using the Responses API.',
    category: 'Responses API',
    tags: ['file-search', 'vector-store', 'responses'],
    code: `from openai import OpenAI
client = OpenAI()

vector_store = client.vector_stores.create(name="a11oy-knowledge-base")

file = client.files.create(
    file=open("governance_policies.pdf", "rb"),
    purpose="assistants",
)
client.vector_stores.files.create(
    vector_store_id=vector_store.id, file_id=file.id
)

response = client.responses.create(
    model="gpt-5.1",
    input="What are the data retention policies for maritime vessels?",
    tools=[{
        "type": "file_search",
        "vector_store_ids": [vector_store.id],
    }],
)

for item in response.output:
    if item.type == "message":
        print(item.content[0].text)
        for ann in item.content[0].text.annotations:
            print(f"  Source: {ann.filename} (score: {ann.score:.2f})")`,
  },
  {
    title: 'Prompt Migration Guide',
    desc: 'Migrate from Chat Completions to the Responses API with minimal changes.',
    category: 'Responses API',
    tags: ['migration', 'chat-completions', 'upgrade'],
    code: `from openai import OpenAI
client = OpenAI()

# OLD: Chat Completions
old_response = client.chat.completions.create(
    model="gpt-5.1",
    messages=[
        {"role": "system", "content": "You are an a11oy analyst."},
        {"role": "user", "content": "Summarize Q4 performance"},
    ],
)

# NEW: Responses API (recommended)
new_response = client.responses.create(
    model="gpt-5.1",
    instructions="You are an a11oy analyst.",
    input="Summarize Q4 performance",
)
print(new_response.output_text)

# With conversation history
new_with_history = client.responses.create(
    model="gpt-5.1",
    instructions="You are an a11oy analyst.",
    input=[
        {"role": "user", "content": "What was Q3 revenue?"},
        {"role": "assistant", "content": "Q3 revenue was \\$4.2B."},
        {"role": "user", "content": "Compare to Q4"},
    ],
)
print(new_with_history.output_text)`,
  },
  {
    title: 'Streaming Completions',
    desc: 'Stream responses with real-time token delivery and event handling.',
    category: 'Responses API',
    tags: ['streaming', 'sse', 'real-time'],
    code: `from openai import OpenAI
client = OpenAI()

stream = client.responses.create(
    model="gpt-5.1",
    input="Write a comprehensive maritime risk report for SZL Holdings",
    stream=True,
)

full_text = ""
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
        full_text += event.delta
    elif event.type == "response.completed":
        print(f"\\n\\nTokens used: {event.response.usage.total_tokens}")

# Async streaming
import asyncio

async def stream_analysis():
    async with client.responses.create(
        model="gpt-5.1",
        input="Analyze fleet utilization trends",
        stream=True,
    ) as stream:
        async for event in stream:
            if hasattr(event, 'delta'):
                print(event.delta, end="", flush=True)

asyncio.run(stream_analysis())`,
  },

  // ─────────────────────────────────────────────────────
  // EVALS & TESTING
  // ─────────────────────────────────────────────────────
  {
    title: 'Custom LLM-as-a-Judge',
    desc: 'Build custom evaluation judges using LLMs to score agent outputs.',
    category: 'Evals & Testing',
    tags: ['evals', 'llm-judge', 'scoring'],
    code: `from openevals import create_llm_as_judge
from a11oy.evals import EvalSuite

judge = create_llm_as_judge(
    prompt="Score the following response for accuracy, "
           "completeness, and adherence to governance policies. "
           "Score 0-1 for each dimension.",
    model="gpt-5.1",
    scoring_type="numeric",
    dimensions=["accuracy", "completeness", "governance"],
)

suite = EvalSuite(name="a11oy-quality-gate")
suite.add_case(
    input="What is the indemnification clause in contract #4521?",
    expected="The indemnification clause in contract #4521 states...",
    evaluator=judge,
)

results = suite.run()
for r in results:
    print(f"Accuracy: {r.scores['accuracy']:.2f}")
    print(f"Completeness: {r.scores['completeness']:.2f}")
    print(f"Governance: {r.scores['governance']:.2f}")`,
  },
  {
    title: 'Realtime Eval Guide',
    desc: 'Evaluate realtime voice agent responses for quality and latency.',
    category: 'Evals & Testing',
    tags: ['realtime', 'voice-eval', 'latency'],
    code: `from openai import OpenAI
from a11oy.evals import RealtimeEval

client = OpenAI()
evaluator = RealtimeEval(
    metrics=["response_latency", "transcription_accuracy",
             "turn_taking", "voice_quality"],
)

test_scenarios = [
    {"input_audio": "audio/vessel_inquiry.wav",
     "expected_intent": "vessel_status_check"},
    {"input_audio": "audio/compliance_question.wav",
     "expected_intent": "compliance_query"},
]

results = evaluator.run_batch(test_scenarios)
for r in results:
    print(f"Scenario: {r.scenario}")
    print(f"  Latency: {r.latency_ms}ms")
    print(f"  Accuracy: {r.accuracy:.2%}")
    print(f"  Turn-taking: {r.turn_taking_score:.2f}")`,
  },
  {
    title: 'Developing Hallucination Guardrails',
    desc: 'Build and test guardrails that detect and prevent hallucinated outputs.',
    category: 'Evals & Testing',
    tags: ['hallucination', 'guardrails', 'eval'],
    code: `from openai import OpenAI
from a11oy.guardrails import HallucinationDetector

client = OpenAI()
detector = HallucinationDetector(
    model="gpt-5.1",
    reference_corpus="vector_store_id",
    threshold=0.85,
)

test_cases = [
    {"claim": "Revenue grew 15% in Q4 2025",
     "source_docs": ["q4_earnings.pdf"]},
    {"claim": "The company was founded in 1847",
     "source_docs": ["company_history.pdf"]},
]

for case in test_cases:
    result = detector.verify(
        claim=case["claim"],
        sources=case["source_docs"],
    )
    print(f"Claim: {case['claim']}")
    print(f"  Supported: {result.is_supported}")
    print(f"  Confidence: {result.confidence:.2%}")
    print(f"  Evidence: {result.evidence[:100]}...")`,
  },
  {
    title: 'Optimize Prompts with Evals',
    desc: 'Use automated prompt optimization to improve agent performance.',
    category: 'Evals & Testing',
    tags: ['prompt-optimization', 'evals', 'automated'],
    code: `from openai import OpenAI
from a11oy.evals import PromptOptimizer

client = OpenAI()
optimizer = PromptOptimizer(
    model="gpt-5.1",
    eval_model="gpt-5.1",
    metric="accuracy",
)

baseline_prompt = "Classify this support ticket by priority."
test_data = [
    {"input": "Server is completely down", "expected": "critical"},
    {"input": "Button color is wrong", "expected": "low"},
    {"input": "Data breach detected", "expected": "critical"},
    {"input": "Typo in footer", "expected": "low"},
]

optimized = optimizer.optimize(
    prompt=baseline_prompt,
    test_cases=test_data,
    iterations=10,
)

print(f"Baseline accuracy: {optimized.baseline_score:.2%}")
print(f"Optimized accuracy: {optimized.best_score:.2%}")
print(f"Best prompt:\\n{optimized.best_prompt}")`,
  },
  {
    title: 'Reinforcement Fine-Tuning Evals',
    desc: 'Evaluate models trained with reinforcement fine-tuning (RFT) on domain tasks.',
    category: 'Evals & Testing',
    tags: ['rft', 'reinforcement', 'eval'],
    code: `from openai import OpenAI
from a11oy.evals import RFTEvalSuite

client = OpenAI()

suite = RFTEvalSuite(
    model="ft:gpt-5.1:a11oy:maritime-rft:abc123",
    baseline_model="gpt-5.1",
    domain="maritime-compliance",
)

suite.add_cases([
    {"input": "Is vessel IMO-9434761 compliant with SOLAS Chapter II-2?",
     "grader": "expert_rubric",
     "rubric": "Must reference specific SOLAS regulations"},
    {"input": "Calculate ballast water exchange requirements for Pacific transit",
     "grader": "numeric_accuracy",
     "expected_range": [95, 100]},
])

results = suite.run(parallel=True)
print(f"RFT model: {results.rft_score:.2%}")
print(f"Baseline:  {results.baseline_score:.2%}")
print(f"Improvement: +{results.improvement:.2%}")`,
  },

  // ─────────────────────────────────────────────────────
  // FINE-TUNING & DISTILLATION
  // ─────────────────────────────────────────────────────
  {
    title: 'Chat Fine-Tuning Data Prep',
    desc: 'Prepare and validate training data for chat model fine-tuning.',
    category: 'Fine-Tuning & Distillation',
    tags: ['fine-tuning', 'data-prep', 'jsonl'],
    code: `import json
from a11oy.finetune import DataValidator

training_data = [
    {"messages": [
        {"role": "system", "content": "You are an a11oy maritime analyst."},
        {"role": "user", "content": "What is the current status of vessel IMO-9434761?"},
        {"role": "assistant", "content": "Vessel IMO-9434761 (MV Pacific Trader) is currently "
                                          "en route to Port of Rotterdam. ETA: 2026-04-28."},
    ]},
    {"messages": [
        {"role": "system", "content": "You are an a11oy maritime analyst."},
        {"role": "user", "content": "Check SOLAS compliance for vessel class A."},
        {"role": "assistant", "content": "Class A vessels must comply with SOLAS Chapters II-1, "
                                          "II-2, III, and XII. Current compliance rate: 98.2%."},
    ]},
]

validator = DataValidator()
report = validator.validate(training_data)
print(f"Valid examples: {report.valid_count}")
print(f"Issues: {report.issues}")

with open("a11oy_maritime_training.jsonl", "w") as f:
    for example in training_data:
        f.write(json.dumps(example) + "\\n")`,
  },
  {
    title: 'Fine-Tune Chat Models',
    desc: 'End-to-end fine-tuning workflow for chat models on domain-specific data.',
    category: 'Fine-Tuning & Distillation',
    tags: ['fine-tuning', 'sft', 'chat'],
    code: `from openai import OpenAI
client = OpenAI()

file = client.files.create(
    file=open("a11oy_maritime_training.jsonl", "rb"),
    purpose="fine-tune",
)

job = client.fine_tuning.jobs.create(
    training_file=file.id,
    model="gpt-4.1-mini",
    hyperparameters={
        "n_epochs": 3,
        "batch_size": 4,
        "learning_rate_multiplier": 1.8,
    },
    suffix="a11oy-maritime",
)

print(f"Job ID: {job.id}")
print(f"Status: {job.status}")

import time
while True:
    job = client.fine_tuning.jobs.retrieve(job.id)
    print(f"Status: {job.status}")
    if job.status in ["succeeded", "failed"]:
        break
    time.sleep(60)

if job.status == "succeeded":
    print(f"Fine-tuned model: {job.fine_tuned_model}")
    response = client.chat.completions.create(
        model=job.fine_tuned_model,
        messages=[{"role": "user", "content": "Check vessel IMO-9434761 status"}],
    )
    print(response.choices[0].message.content)`,
  },
  {
    title: 'DPO Fine-Tuning Guide',
    desc: 'Direct Preference Optimization to align models with human preferences.',
    category: 'Fine-Tuning & Distillation',
    tags: ['dpo', 'alignment', 'preferences'],
    code: `from openai import OpenAI
client = OpenAI()

# DPO training data format: chosen vs rejected pairs
dpo_data = [
    {"input": [
        {"role": "user", "content": "Assess risk for vessel transit through Hormuz Strait"},
    ],
     "preferred_output": [
        {"role": "assistant", "content": "Risk Assessment (HIGH):\\n"
         "1. Geopolitical: Elevated tension in Strait of Hormuz\\n"
         "2. Insurance: War risk premium at 0.5%\\n"
         "3. Recommendation: Route via Cape of Good Hope"},
     ],
     "non_preferred_output": [
        {"role": "assistant", "content": "It might be risky. Consider alternatives."},
     ]},
]

file = client.files.create(
    file=open("a11oy_dpo_pairs.jsonl", "rb"), purpose="fine-tune"
)

job = client.fine_tuning.jobs.create(
    training_file=file.id,
    model="gpt-4.1",
    method={"type": "dpo", "dpo": {"hyperparameters": {"beta": 0.1}}},
    suffix="a11oy-aligned",
)
print(f"DPO Job: {job.id} — {job.status}")`,
  },
  {
    title: 'Model Distillation',
    desc: 'Distill a large model into a smaller, faster one while preserving quality.',
    category: 'Fine-Tuning & Distillation',
    tags: ['distillation', 'compression', 'efficiency'],
    code: `from openai import OpenAI
client = OpenAI()

# Step 1: Generate training data from teacher model
teacher_responses = []
prompts = [
    "Analyze maritime insurance claim #4521",
    "Calculate port congestion risk for Rotterdam",
    "Evaluate SOLAS compliance for bulk carriers",
]

for prompt in prompts:
    resp = client.responses.create(
        model="gpt-5.1",  # teacher
        input=prompt,
        store=True,  # store for distillation
    )
    teacher_responses.append({
        "input": prompt,
        "output": resp.output_text,
    })

# Step 2: Create distillation fine-tune
file = client.files.create(
    file=open("teacher_outputs.jsonl", "rb"), purpose="fine-tune"
)

job = client.fine_tuning.jobs.create(
    training_file=file.id,
    model="gpt-4.1-mini",  # student
    method={"type": "distillation"},
    suffix="a11oy-compressed",
)
print(f"Distillation job: {job.id}")`,
  },
  {
    title: 'Fine-Tuning for Function Calling',
    desc: 'Fine-tune models specifically for reliable function/tool calling.',
    category: 'Fine-Tuning & Distillation',
    tags: ['function-calling', 'fine-tuning', 'tools'],
    code: `from openai import OpenAI
import json
client = OpenAI()

training_examples = [
    {"messages": [
        {"role": "system", "content": "You are an a11oy assistant with access to tools."},
        {"role": "user", "content": "Look up vessel IMO 9434761"},
        {"role": "assistant", "content": None,
         "function_call": {"name": "vessel_lookup",
                           "arguments": json.dumps({"imo": "9434761"})}},
        {"role": "function", "name": "vessel_lookup",
         "content": json.dumps({"name": "MV Pacific Trader", "status": "en_route"})},
        {"role": "assistant", "content": "MV Pacific Trader (IMO 9434761) is currently en route."},
    ]},
]

with open("function_calling_train.jsonl", "w") as f:
    for ex in training_examples:
        f.write(json.dumps(ex) + "\\n")

file = client.files.create(
    file=open("function_calling_train.jsonl", "rb"), purpose="fine-tune"
)
job = client.fine_tuning.jobs.create(
    training_file=file.id, model="gpt-4.1-mini",
    suffix="a11oy-tools",
)
print(f"Tool fine-tune: {job.id}")`,
  },
  {
    title: 'Fine-Tuned Classification',
    desc: 'Fine-tune a model for high-accuracy text classification tasks.',
    category: 'Fine-Tuning & Distillation',
    tags: ['classification', 'fine-tuning', 'accuracy'],
    code: `from openai import OpenAI
import json
client = OpenAI()

categories = ["critical", "high", "medium", "low", "info"]
training_data = [
    {"messages": [
        {"role": "system", "content": f"Classify into: {', '.join(categories)}"},
        {"role": "user", "content": "Engine failure detected on vessel IMO-9434761"},
        {"role": "assistant", "content": "critical"},
    ]},
    {"messages": [
        {"role": "system", "content": f"Classify into: {', '.join(categories)}"},
        {"role": "user", "content": "Quarterly maintenance schedule updated"},
        {"role": "assistant", "content": "info"},
    ]},
]

with open("classification_train.jsonl", "w") as f:
    for ex in training_data:
        f.write(json.dumps(ex) + "\\n")

file = client.files.create(
    file=open("classification_train.jsonl", "rb"), purpose="fine-tune"
)
job = client.fine_tuning.jobs.create(
    training_file=file.id, model="gpt-4.1-mini",
    suffix="a11oy-classifier",
)
print(f"Classifier fine-tune: {job.id}")`,
  },

  // ─────────────────────────────────────────────────────
  // REALTIME & VOICE
  // ─────────────────────────────────────────────────────
  {
    title: 'Realtime Voice Agent',
    desc: 'Build a voice-first agent with WebSocket-based realtime API.',
    category: 'Realtime & Voice',
    tags: ['realtime', 'voice', 'websocket'],
    code: `import asyncio
import websockets
import json
import base64

async def run_voice_agent():
    url = "wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview"
    headers = {"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"],
               "OpenAI-Beta": "realtime=v1"}

    async with websockets.connect(url, extra_headers=headers) as ws:
        await ws.send(json.dumps({
            "type": "session.update",
            "session": {
                "modalities": ["text", "audio"],
                "instructions": "You are an a11oy maritime operations assistant. "
                                "Help users with vessel tracking, port schedules, "
                                "and compliance queries. Speak clearly and concisely.",
                "voice": "alloy",
                "turn_detection": {"type": "server_vad"},
            }
        }))

        async for message in ws:
            event = json.loads(message)
            if event["type"] == "response.audio.delta":
                audio_bytes = base64.b64decode(event["delta"])
                play_audio(audio_bytes)
            elif event["type"] == "response.text.delta":
                print(event["delta"], end="", flush=True)

asyncio.run(run_voice_agent())`,
  },
  {
    title: 'Context Summarization with Realtime API',
    desc: 'Maintain conversation context in long realtime sessions with summarization.',
    category: 'Realtime & Voice',
    tags: ['realtime', 'summarization', 'context'],
    code: `from openai import OpenAI
import asyncio

client = OpenAI()

class RealtimeContextManager:
    def __init__(self, max_turns=20):
        self.turns = []
        self.max_turns = max_turns
        self.summary = ""

    async def add_turn(self, role, content):
        self.turns.append({"role": role, "content": content})
        if len(self.turns) > self.max_turns:
            await self.summarize()

    async def summarize(self):
        old_turns = self.turns[:len(self.turns)//2]
        resp = client.responses.create(
            model="gpt-4.1-mini",
            input=f"Summarize this conversation concisely:\\n"
                  + "\\n".join(f"{t['role']}: {t['content']}" for t in old_turns),
        )
        self.summary = resp.output_text
        self.turns = self.turns[len(self.turns)//2:]
        print(f"Context summarized: {len(self.summary)} chars")

    def get_context(self):
        ctx = []
        if self.summary:
            ctx.append({"role": "system", "content": f"Previous context: {self.summary}"})
        ctx.extend(self.turns)
        return ctx

manager = RealtimeContextManager(max_turns=15)`,
  },
  {
    title: 'Speech Transcription Methods',
    desc: 'Compare and implement multiple speech transcription approaches.',
    category: 'Realtime & Voice',
    tags: ['transcription', 'whisper', 'speech'],
    code: `from openai import OpenAI
client = OpenAI()

# Method 1: Standard Whisper transcription
with open("bridge_recording.mp3", "rb") as audio:
    transcript = client.audio.transcriptions.create(
        model="whisper-1",
        file=audio,
        language="en",
        response_format="verbose_json",
        timestamp_granularities=["word", "segment"],
    )

for segment in transcript.segments:
    print(f"[{segment.start:.1f}s - {segment.end:.1f}s] {segment.text}")

# Method 2: Realtime out-of-band transcription
response = client.responses.create(
    model="gpt-5.1-audio-preview",
    input=[{
        "role": "user",
        "content": [
            {"type": "input_audio",
             "input_audio": {"data": audio_b64, "format": "mp3"}},
            {"type": "text",
             "text": "Transcribe this maritime bridge recording. "
                     "Flag any safety-critical communications."},
        ],
    }],
)
print(response.output_text)`,
  },
  {
    title: 'Steering Text-to-Speech',
    desc: 'Control TTS voice characteristics, pacing, and emotion.',
    category: 'Realtime & Voice',
    tags: ['tts', 'voice', 'steering'],
    code: `from openai import OpenAI
from pathlib import Path
client = OpenAI()

# Standard TTS
speech = client.audio.speech.create(
    model="tts-1-hd",
    voice="alloy",
    input="Attention all hands: vessel approaching port. "
          "Reduce speed to 5 knots. Harbor pilot boarding at 0800.",
    speed=0.9,
)
Path("announcement.mp3").write_bytes(speech.content)

# Voice translation
for lang, voice in [("es", "nova"), ("fr", "shimmer"), ("ja", "echo")]:
    translated = client.responses.create(
        model="gpt-5.1",
        input=f"Translate to {lang}: 'All vessels must comply with new emissions regulations'",
    )
    speech = client.audio.speech.create(
        model="tts-1-hd", voice=voice,
        input=translated.output_text,
    )
    Path(f"announcement_{lang}.mp3").write_bytes(speech.content)
    print(f"Generated {lang} announcement with voice {voice}")`,
  },
  {
    title: 'Data-Intensive Realtime Apps',
    desc: 'Build realtime applications that process high-volume streaming data.',
    category: 'Realtime & Voice',
    tags: ['realtime', 'streaming', 'data-intensive'],
    code: `import asyncio
import json
from openai import AsyncOpenAI

client = AsyncOpenAI()

async def process_vessel_stream():
    """Process real-time AIS vessel position data with AI analysis."""
    positions = []

    async def analyze_batch(batch):
        resp = await client.responses.create(
            model="gpt-4.1-mini",
            input=json.dumps(batch),
            instructions="Analyze these vessel positions for anomalies. "
                         "Flag unusual speed changes, route deviations, "
                         "or proximity warnings.",
        )
        return resp.output_text

    async for position in ais_stream():
        positions.append(position)
        if len(positions) >= 50:
            analysis = await analyze_batch(positions)
            if "ALERT" in analysis:
                await send_alert(analysis)
            positions = []
            print(f"Batch analyzed: {analysis[:100]}...")

asyncio.run(process_vessel_stream())`,
  },

  // ─────────────────────────────────────────────────────
  // MULTIMODAL & VISION
  // ─────────────────────────────────────────────────────
  {
    title: 'GPT Vision for Video Understanding',
    desc: 'Analyze video content frame-by-frame with GPT vision capabilities.',
    category: 'Multimodal & Vision',
    tags: ['vision', 'video', 'analysis'],
    code: `from openai import OpenAI
import cv2
import base64

client = OpenAI()

def extract_frames(video_path, interval_seconds=5):
    cap = cv2.VideoCapture(video_path)
    fps = cap.get(cv2.CAP_PROP_FPS)
    frames = []
    frame_count = 0
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        if frame_count % int(fps * interval_seconds) == 0:
            _, buffer = cv2.imencode('.jpg', frame)
            frames.append(base64.b64encode(buffer).decode())
        frame_count += 1
    cap.release()
    return frames

frames = extract_frames("port_surveillance.mp4", interval_seconds=10)

response = client.responses.create(
    model="gpt-5.1",
    input=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "Analyze this port surveillance footage. "
                                      "Identify vessels, cargo operations, and safety concerns."},
            *[{"type": "image_url",
               "image_url": {"url": f"data:image/jpeg;base64,{f}"}}
              for f in frames[:20]],
        ],
    }],
)
print(response.output_text)`,
  },
  {
    title: 'Tag & Caption Images with Vision',
    desc: 'Automatically tag, caption, and categorize images using GPT-4 Vision.',
    category: 'Multimodal & Vision',
    tags: ['vision', 'tagging', 'captioning'],
    code: `from openai import OpenAI
from pydantic import BaseModel
from typing import List
import base64

client = OpenAI()

class ImageAnalysis(BaseModel):
    caption: str
    tags: List[str]
    category: str
    objects_detected: List[str]
    safety_concerns: List[str]

def analyze_image(image_path: str) -> ImageAnalysis:
    with open(image_path, "rb") as f:
        img_b64 = base64.b64encode(f.read()).decode()

    response = client.responses.create(
        model="gpt-5.1",
        input=[{
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this image. Provide a caption, tags, "
                                          "category, detected objects, and safety concerns."},
                {"type": "image_url",
                 "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"}},
            ],
        }],
        text={"format": {"type": "json_schema",
              "schema": ImageAnalysis.model_json_schema()}},
    )
    return ImageAnalysis.model_validate_json(response.output_text)

result = analyze_image("vessel_inspection.jpg")
print(f"Caption: {result.caption}")
print(f"Tags: {', '.join(result.tags)}")
print(f"Safety: {result.safety_concerns}")`,
  },
  {
    title: 'RAG Outfit Assistant with Vision',
    desc: 'Combine vision with RAG for visual + document understanding.',
    category: 'Multimodal & Vision',
    tags: ['vision', 'rag', 'multimodal'],
    code: `from openai import OpenAI
import base64

client = OpenAI()

vector_store = client.vector_stores.create(name="a11oy-visual-docs")
# Upload technical diagrams, schematics, manuals
for doc in ["engine_manual.pdf", "safety_diagrams.pdf"]:
    f = client.files.create(file=open(doc, "rb"), purpose="assistants")
    client.vector_stores.files.create(
        vector_store_id=vector_store.id, file_id=f.id
    )

with open("engine_photo.jpg", "rb") as img:
    img_b64 = base64.b64encode(img.read()).decode()

response = client.responses.create(
    model="gpt-5.1",
    input=[{
        "role": "user",
        "content": [
            {"type": "text",
             "text": "I took this photo of our engine compartment. "
                     "What maintenance issues do you see? "
                     "Cross-reference with our maintenance manual."},
            {"type": "image_url",
             "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"}},
        ],
    }],
    tools=[{
        "type": "file_search",
        "vector_store_ids": [vector_store.id],
    }],
)
print(response.output_text)`,
  },
  {
    title: 'Generate Images with GPT Image',
    desc: 'Generate and edit images using the GPT Image model.',
    category: 'Multimodal & Vision',
    tags: ['image-gen', 'dall-e', 'gpt-image'],
    code: `from openai import OpenAI
import base64

client = OpenAI()

# Generate image
response = client.images.generate(
    model="gpt-image-1",
    prompt="A sleek modern command center dashboard showing maritime vessel tracking, "
           "dark theme with gold (#c9b787) accents, minimalist enterprise design, "
           "multiple screens showing maps and analytics",
    size="1536x1024",
    quality="high",
    n=1,
)

# Save generated image
image_b64 = response.data[0].b64_json
with open("command_center.png", "wb") as f:
    f.write(base64.b64decode(image_b64))

# Edit existing image
with open("dashboard_screenshot.png", "rb") as f:
    edit_response = client.images.edit(
        model="gpt-image-1",
        image=f,
        prompt="Add a gold-accented alert notification panel on the right side",
    )
print(f"Generated {len(response.data)} image(s)")`,
  },
  {
    title: 'High Input Fidelity Image Generation',
    desc: 'Generate images with precise input fidelity for brand-consistent outputs.',
    category: 'Multimodal & Vision',
    tags: ['image-gen', 'fidelity', 'brand'],
    code: `from openai import OpenAI
import base64

client = OpenAI()

# Reference image for style matching
with open("a11oy_brand_reference.png", "rb") as f:
    ref_b64 = base64.b64encode(f.read()).decode()

response = client.responses.create(
    model="gpt-5.1",
    input=[{
        "role": "user",
        "content": [
            {"type": "text",
             "text": "Generate a new marketing image matching this exact brand style. "
                     "Dark (#0a0a0a) background, muted gold (#c9b787) accents, "
                     "minimalist enterprise aesthetic. Show a futuristic AI command center."},
            {"type": "image_url",
             "image_url": {"url": f"data:image/png;base64,{ref_b64}"}},
        ],
    }],
    tools=[{"type": "image_generation",
            "quality": "high", "size": "1536x1024"}],
)

for item in response.output:
    if item.type == "image_generation_call":
        with open("brand_consistent_output.png", "wb") as f:
            f.write(base64.b64decode(item.result))
        print("Brand-consistent image generated")`,
  },
  {
    title: 'Parse PDF Documents for RAG',
    desc: 'Extract structured data from PDFs for retrieval-augmented generation.',
    category: 'Multimodal & Vision',
    tags: ['pdf', 'parsing', 'extraction'],
    code: `from openai import OpenAI
import base64

client = OpenAI()

def parse_pdf_with_vision(pdf_path: str) -> dict:
    """Extract structured data from PDF using vision."""
    import fitz  # PyMuPDF
    doc = fitz.open(pdf_path)
    pages = []

    for page_num in range(min(len(doc), 20)):
        page = doc[page_num]
        pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
        img_b64 = base64.b64encode(pix.tobytes("png")).decode()

        resp = client.responses.create(
            model="gpt-5.1",
            input=[{
                "role": "user",
                "content": [
                    {"type": "text",
                     "text": "Extract all text, tables, and key data from this page. "
                             "Format tables as JSON arrays."},
                    {"type": "image_url",
                     "image_url": {"url": f"data:image/png;base64,{img_b64}"}},
                ],
            }],
        )
        pages.append({"page": page_num + 1, "content": resp.output_text})

    return {"document": pdf_path, "pages": pages}

result = parse_pdf_with_vision("contract_4521.pdf")
print(f"Extracted {len(result['pages'])} pages")`,
  },

  // ─────────────────────────────────────────────────────
  // RAG & SEARCH
  // ─────────────────────────────────────────────────────
  {
    title: 'Question Answering with Embeddings',
    desc: 'Build a Q&A system using embeddings for semantic search over documents.',
    category: 'RAG & Search',
    tags: ['embeddings', 'qa', 'semantic-search'],
    code: `from openai import OpenAI
import numpy as np

client = OpenAI()

def get_embedding(text, model="text-embedding-3-large"):
    return client.embeddings.create(input=text, model=model).data[0].embedding

def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

knowledge_base = [
    "SOLAS Chapter II-1 covers ship construction and stability requirements.",
    "Ballast water management convention requires treatment systems on all vessels.",
    "ISM Code mandates a Safety Management System for all vessels over 500 GT.",
    "MARPOL Annex VI sets limits on SOx and NOx emissions from ships.",
]

kb_embeddings = [get_embedding(doc) for doc in knowledge_base]

def answer_question(question: str) -> str:
    q_emb = get_embedding(question)
    scores = [cosine_similarity(q_emb, doc_emb) for doc_emb in kb_embeddings]
    best_idx = np.argmax(scores)
    context = knowledge_base[best_idx]

    response = client.responses.create(
        model="gpt-5.1",
        input=f"Context: {context}\\n\\nQuestion: {question}",
        instructions="Answer based on the provided context only.",
    )
    return response.output_text

answer = answer_question("What are the emissions regulations for ships?")
print(answer)`,
  },
  {
    title: 'RAG with Graph Database',
    desc: 'Combine graph databases with RAG for relationship-aware retrieval.',
    category: 'RAG & Search',
    tags: ['graph-db', 'rag', 'neo4j'],
    code: `from openai import OpenAI
from neo4j import GraphDatabase

client = OpenAI()
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

def query_graph(question: str) -> str:
    """Convert natural language to Cypher and query the graph."""
    cypher_resp = client.responses.create(
        model="gpt-5.1",
        input=f"Convert to Cypher query: {question}",
        instructions="Generate a Neo4j Cypher query. The graph has nodes: "
                     "Vessel, Port, Company, Route, Regulation. "
                     "Relationships: DOCKED_AT, OWNED_BY, TRANSITS, COMPLIES_WITH.",
    )
    cypher = cypher_resp.output_text.strip().strip('\`')

    with driver.session() as session:
        results = session.run(cypher)
        data = [dict(record) for record in results]

    answer_resp = client.responses.create(
        model="gpt-5.1",
        input=f"Question: {question}\\nGraph data: {data}",
        instructions="Answer the question using the graph query results.",
    )
    return answer_resp.output_text

answer = query_graph("Which vessels owned by SZL Holdings visited Rotterdam in 2025?")
print(answer)`,
  },
  {
    title: 'Question Answering with Search API',
    desc: 'Build Q&A using web search for real-time information retrieval.',
    category: 'RAG & Search',
    tags: ['search', 'web', 'qa'],
    code: `from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-5.1",
    input="What are the latest IMO regulations for 2026 "
          "regarding carbon intensity indicators?",
    tools=[{"type": "web_search_preview"}],
    instructions="Search for the most current maritime regulations. "
                 "Cite your sources with URLs.",
)

print(response.output_text)

for item in response.output:
    if item.type == "web_search_call":
        print(f"\\nSearch query: {item.query}")
        for result in item.results:
            print(f"  - {result.title}: {result.url}")`,
  },
  {
    title: 'Embedding Wikipedia for Search',
    desc: 'Embed and index large document collections for semantic search.',
    category: 'RAG & Search',
    tags: ['embeddings', 'wikipedia', 'indexing'],
    code: `from openai import OpenAI
import pandas as pd
import numpy as np

client = OpenAI()

def batch_embed(texts, model="text-embedding-3-large", batch_size=100):
    """Embed texts in batches for efficiency."""
    all_embeddings = []
    for i in range(0, len(texts), batch_size):
        batch = texts[i:i+batch_size]
        response = client.embeddings.create(input=batch, model=model)
        all_embeddings.extend([d.embedding for d in response.data])
        print(f"Embedded {min(i+batch_size, len(texts))}/{len(texts)}")
    return all_embeddings

# Load maritime knowledge base
articles = pd.read_csv("maritime_knowledge.csv")
print(f"Embedding {len(articles)} articles...")

embeddings = batch_embed(articles["content"].tolist())
articles["embedding"] = embeddings

# Save for later retrieval
articles.to_parquet("maritime_embeddings.parquet")
print(f"Saved {len(articles)} article embeddings")`,
  },
  {
    title: 'Search Reranking with Cross-Encoders',
    desc: 'Improve search quality with cross-encoder reranking after initial retrieval.',
    category: 'RAG & Search',
    tags: ['reranking', 'cross-encoder', 'search'],
    code: `from openai import OpenAI
import numpy as np

client = OpenAI()

def search_and_rerank(query, documents, top_k=5):
    """Two-stage retrieval: embedding search + LLM reranking."""
    # Stage 1: Fast embedding search
    q_emb = client.embeddings.create(
        input=query, model="text-embedding-3-large"
    ).data[0].embedding

    scores = []
    for doc in documents:
        similarity = np.dot(q_emb, doc["embedding"])
        scores.append((doc, similarity))

    candidates = sorted(scores, key=lambda x: x[1], reverse=True)[:top_k*3]

    # Stage 2: LLM reranking
    rerank_input = "\\n".join(
        f"[{i}] {doc['text'][:200]}"
        for i, (doc, _) in enumerate(candidates)
    )

    response = client.responses.create(
        model="gpt-4.1-mini",
        input=f"Query: {query}\\n\\nDocuments:\\n{rerank_input}",
        instructions="Rank these documents by relevance to the query. "
                     "Return indices in order of relevance.",
    )

    reranked_indices = [int(x) for x in response.output_text.split(",")[:top_k]]
    return [candidates[i][0] for i in reranked_indices]

results = search_and_rerank("SOLAS compliance requirements", maritime_docs)
for r in results:
    print(f"- {r['title']}")`,
  },

  // ─────────────────────────────────────────────────────
  // EMBEDDINGS & CLUSTERING
  // ─────────────────────────────────────────────────────
  {
    title: 'Classification Using Embeddings',
    desc: 'Use embeddings for zero-shot and few-shot text classification.',
    category: 'Embeddings & Clustering',
    tags: ['embeddings', 'classification', 'zero-shot'],
    code: `from openai import OpenAI
import numpy as np

client = OpenAI()

categories = {
    "safety_alert": "Urgent safety notification about vessel or crew danger",
    "maintenance": "Scheduled or unscheduled maintenance report",
    "compliance": "Regulatory compliance update or violation notice",
    "operations": "Daily operational status or route update",
    "financial": "Cost, revenue, or budget-related communication",
}

cat_embeddings = {
    cat: client.embeddings.create(
        input=desc, model="text-embedding-3-large"
    ).data[0].embedding
    for cat, desc in categories.items()
}

def classify(text):
    text_emb = client.embeddings.create(
        input=text, model="text-embedding-3-large"
    ).data[0].embedding

    scores = {
        cat: np.dot(text_emb, emb) / (np.linalg.norm(text_emb) * np.linalg.norm(emb))
        for cat, emb in cat_embeddings.items()
    }
    return max(scores, key=scores.get), max(scores.values())

text = "Fire suppression system inspection due next week on Deck 3"
category, confidence = classify(text)
print(f"Category: {category} (confidence: {confidence:.3f})")`,
  },
  {
    title: 'Clustering for Transaction Classification',
    desc: 'Use embedding clustering to automatically categorize transactions.',
    category: 'Embeddings & Clustering',
    tags: ['clustering', 'k-means', 'transactions'],
    code: `from openai import OpenAI
from sklearn.cluster import KMeans
import numpy as np

client = OpenAI()

transactions = [
    "Port docking fee - Rotterdam - \\$45,000",
    "Fuel bunker purchase - Singapore - \\$180,000",
    "Crew salary disbursement - March 2026",
    "Hull insurance premium - Annual renewal",
    "Cargo loading crane rental - Hamburg",
    "Navigation equipment maintenance",
    "Port authority regulatory inspection fee",
    "Bunker fuel surcharge - Pacific route",
]

embeddings = client.embeddings.create(
    input=transactions, model="text-embedding-3-large"
).data

emb_matrix = np.array([e.embedding for e in embeddings])

kmeans = KMeans(n_clusters=4, random_state=42)
labels = kmeans.fit_predict(emb_matrix)

clusters = {}
for text, label in zip(transactions, labels):
    clusters.setdefault(label, []).append(text)

for cluster_id, items in clusters.items():
    # Auto-name cluster using LLM
    resp = client.responses.create(
        model="gpt-4.1-mini",
        input=f"Give a short category name for these transactions: {items}",
    )
    print(f"\\nCluster '{resp.output_text}':")
    for item in items:
        print(f"  - {item}")`,
  },
  {
    title: 'Customizing Embeddings',
    desc: 'Fine-tune embedding models for domain-specific semantic similarity.',
    category: 'Embeddings & Clustering',
    tags: ['embeddings', 'custom', 'fine-tuning'],
    code: `from openai import OpenAI
import numpy as np

client = OpenAI()

# text-embedding-3-large supports dimension reduction
def get_embedding(text, dimensions=256):
    return client.embeddings.create(
        input=text,
        model="text-embedding-3-large",
        dimensions=dimensions,  # 256, 1024, or 3072
    ).data[0].embedding

# Compare similarity at different dimension sizes
text_a = "Vessel IMO-9434761 ballast water treatment system"
text_b = "Ship water ballast management equipment"
text_c = "Quarterly financial earnings report"

for dims in [256, 1024, 3072]:
    emb_a = get_embedding(text_a, dims)
    emb_b = get_embedding(text_b, dims)
    emb_c = get_embedding(text_c, dims)

    sim_ab = np.dot(emb_a, emb_b) / (np.linalg.norm(emb_a) * np.linalg.norm(emb_b))
    sim_ac = np.dot(emb_a, emb_c) / (np.linalg.norm(emb_a) * np.linalg.norm(emb_c))
    print(f"Dims={dims}: similar={sim_ab:.3f}, dissimilar={sim_ac:.3f}")`,
  },
  {
    title: 'Embedding Long Inputs',
    desc: 'Handle documents that exceed the embedding model token limit.',
    category: 'Embeddings & Clustering',
    tags: ['embeddings', 'chunking', 'long-text'],
    code: `from openai import OpenAI
import tiktoken
import numpy as np

client = OpenAI()
enc = tiktoken.encoding_for_model("text-embedding-3-large")

def chunk_text(text, max_tokens=8000, overlap=200):
    tokens = enc.encode(text)
    chunks = []
    start = 0
    while start < len(tokens):
        end = min(start + max_tokens, len(tokens))
        chunk = enc.decode(tokens[start:end])
        chunks.append(chunk)
        start = end - overlap
    return chunks

def embed_long_document(text):
    chunks = chunk_text(text)
    embeddings = []
    for chunk in chunks:
        emb = client.embeddings.create(
            input=chunk, model="text-embedding-3-large"
        ).data[0].embedding
        embeddings.append(emb)

    # Average embeddings weighted by chunk length
    weights = [len(c) for c in chunks]
    weighted = np.average(embeddings, axis=0, weights=weights)
    return weighted / np.linalg.norm(weighted)

long_doc = open("maritime_regulation_full.txt").read()
doc_embedding = embed_long_document(long_doc)
print(f"Document embedding: {len(doc_embedding)} dimensions")`,
  },
  {
    title: 'Code Search Using Embeddings',
    desc: 'Build a semantic code search engine using embeddings.',
    category: 'Embeddings & Clustering',
    tags: ['embeddings', 'code-search', 'semantic'],
    code: `from openai import OpenAI
import numpy as np
import os

client = OpenAI()

def index_codebase(directory):
    files = []
    for root, _, filenames in os.walk(directory):
        for f in filenames:
            if f.endswith(('.py', '.ts', '.tsx')):
                path = os.path.join(root, f)
                content = open(path).read()
                files.append({"path": path, "content": content[:4000]})

    embeddings = client.embeddings.create(
        input=[f["content"] for f in files],
        model="text-embedding-3-large",
    ).data

    for f, e in zip(files, embeddings):
        f["embedding"] = e.embedding
    return files

def search_code(query, index, top_k=5):
    q_emb = client.embeddings.create(
        input=query, model="text-embedding-3-large"
    ).data[0].embedding

    scores = [(f, np.dot(q_emb, f["embedding"])) for f in index]
    top = sorted(scores, key=lambda x: x[1], reverse=True)[:top_k]
    return [(f["path"], score) for f, score in top]

index = index_codebase("src/")
results = search_code("vessel tracking real-time updates", index)
for path, score in results:
    print(f"{score:.3f} {path}")`,
  },
  {
    title: 'Recommendation Using Embeddings',
    desc: 'Build a content recommendation engine using embedding similarity.',
    category: 'Embeddings & Clustering',
    tags: ['embeddings', 'recommendation', 'similarity'],
    code: `from openai import OpenAI
import numpy as np

client = OpenAI()

articles = [
    {"id": 1, "title": "SOLAS Chapter II-1 Updates 2026",
     "content": "New structural requirements for bulk carriers..."},
    {"id": 2, "title": "IMO Carbon Intensity Indicator Guide",
     "content": "CII rating methodology and improvement strategies..."},
    {"id": 3, "title": "Ballast Water Management Best Practices",
     "content": "Treatment systems comparison and compliance tips..."},
    {"id": 4, "title": "Maritime Cyber Security Framework",
     "content": "Protecting vessel OT systems from cyber threats..."},
]

embeddings = client.embeddings.create(
    input=[a["content"] for a in articles],
    model="text-embedding-3-large",
).data

for a, e in zip(articles, embeddings):
    a["embedding"] = e.embedding

def recommend(article_id, top_k=3):
    source = next(a for a in articles if a["id"] == article_id)
    scores = []
    for a in articles:
        if a["id"] != article_id:
            sim = np.dot(source["embedding"], a["embedding"])
            scores.append((a, sim))
    return sorted(scores, key=lambda x: x[1], reverse=True)[:top_k]

recs = recommend(1)
for a, score in recs:
    print(f"  {score:.3f} — {a['title']}")`,
  },

  // ─────────────────────────────────────────────────────
  // VECTOR DATABASES
  // ─────────────────────────────────────────────────────
  {
    title: 'Pinecone Vector Search',
    desc: 'Use Pinecone for scalable vector similarity search with OpenAI embeddings.',
    category: 'Vector Databases',
    tags: ['pinecone', 'vector-db', 'search'],
    code: `from openai import OpenAI
from pinecone import Pinecone

client = OpenAI()
pc = Pinecone(api_key="your-key")

index = pc.Index("a11oy-knowledge")

def upsert_documents(documents):
    for i, doc in enumerate(documents):
        emb = client.embeddings.create(
            input=doc["text"], model="text-embedding-3-large"
        ).data[0].embedding

        index.upsert(vectors=[{
            "id": f"doc-{i}",
            "values": emb,
            "metadata": {"text": doc["text"], "source": doc["source"]},
        }])

def search(query, top_k=5):
    q_emb = client.embeddings.create(
        input=query, model="text-embedding-3-large"
    ).data[0].embedding

    results = index.query(vector=q_emb, top_k=top_k, include_metadata=True)
    return [(m.metadata["text"], m.score) for m in results.matches]

results = search("Maritime emissions compliance requirements")
for text, score in results:
    print(f"[{score:.3f}] {text[:100]}...")`,
  },
  {
    title: 'Qdrant Vector Search',
    desc: 'Build semantic search with Qdrant vector database and filtered queries.',
    category: 'Vector Databases',
    tags: ['qdrant', 'vector-db', 'filtered-search'],
    code: `from openai import OpenAI
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct, Filter, FieldCondition

client = OpenAI()
qdrant = QdrantClient(host="localhost", port=6333)

qdrant.create_collection(
    collection_name="a11oy_docs",
    vectors_config=VectorParams(size=3072, distance=Distance.COSINE),
)

def index_document(doc_id, text, metadata):
    emb = client.embeddings.create(
        input=text, model="text-embedding-3-large"
    ).data[0].embedding

    qdrant.upsert(
        collection_name="a11oy_docs",
        points=[PointStruct(id=doc_id, vector=emb, payload={
            "text": text, **metadata
        })],
    )

def search(query, domain=None, top_k=5):
    q_emb = client.embeddings.create(
        input=query, model="text-embedding-3-large"
    ).data[0].embedding

    filters = None
    if domain:
        filters = Filter(must=[
            FieldCondition(key="domain", match={"value": domain})
        ])

    return qdrant.search(
        collection_name="a11oy_docs", query_vector=q_emb,
        query_filter=filters, limit=top_k,
    )

results = search("vessel compliance", domain="maritime")
for r in results:
    print(f"[{r.score:.3f}] {r.payload['text'][:100]}")`,
  },
  {
    title: 'Weaviate Hybrid Search',
    desc: 'Combine keyword and vector search with Weaviate for hybrid retrieval.',
    category: 'Vector Databases',
    tags: ['weaviate', 'hybrid', 'vector-db'],
    code: `import weaviate
from openai import OpenAI

client = OpenAI()
wv_client = weaviate.connect_to_local()

collection = wv_client.collections.create(
    name="A11oyDocument",
    vectorizer_config=weaviate.classes.config.Configure.Vectorizer.none(),
    properties=[
        weaviate.classes.config.Property(name="text", data_type=weaviate.classes.config.DataType.TEXT),
        weaviate.classes.config.Property(name="domain", data_type=weaviate.classes.config.DataType.TEXT),
    ],
)

def hybrid_search(query, alpha=0.5, limit=5):
    """alpha=1.0 is pure vector, alpha=0.0 is pure keyword"""
    q_emb = client.embeddings.create(
        input=query, model="text-embedding-3-large"
    ).data[0].embedding

    results = collection.query.hybrid(
        query=query,
        vector=q_emb,
        alpha=alpha,
        limit=limit,
    )
    return results.objects

results = hybrid_search("SOLAS fire safety inspection", alpha=0.7)
for r in results:
    print(f"- {r.properties['text'][:100]}")

wv_client.close()`,
  },
  {
    title: 'Redis Vector Search',
    desc: 'Use Redis as a high-performance vector database for embeddings search.',
    category: 'Vector Databases',
    tags: ['redis', 'vector-db', 'performance'],
    code: `from openai import OpenAI
import redis
import numpy as np
from redis.commands.search.field import VectorField, TextField
from redis.commands.search.query import Query

client = OpenAI()
r = redis.Redis(host="localhost", port=6379)

# Create index
r.ft("a11oy_idx").create_index([
    TextField("text"),
    TextField("domain"),
    VectorField("embedding", "HNSW", {
        "TYPE": "FLOAT32", "DIM": 3072, "DISTANCE_METRIC": "COSINE"
    }),
])

def index_doc(doc_id, text, domain):
    emb = client.embeddings.create(
        input=text, model="text-embedding-3-large"
    ).data[0].embedding
    emb_bytes = np.array(emb, dtype=np.float32).tobytes()

    r.hset(f"doc:{doc_id}", mapping={
        "text": text, "domain": domain, "embedding": emb_bytes,
    })

def search(query, top_k=5):
    q_emb = client.embeddings.create(
        input=query, model="text-embedding-3-large"
    ).data[0].embedding
    q_bytes = np.array(q_emb, dtype=np.float32).tobytes()

    q = Query(f"*=>[KNN {top_k} @embedding $vec AS score]").return_fields("text", "score")
    results = r.ft("a11oy_idx").search(q, query_params={"vec": q_bytes})
    for doc in results.docs:
        print(f"[{doc.score}] {doc.text[:100]}")

search("maritime vessel tracking compliance")`,
  },
  {
    title: 'Elasticsearch Semantic Search',
    desc: 'Build semantic search with Elasticsearch and OpenAI embeddings.',
    category: 'Vector Databases',
    tags: ['elasticsearch', 'semantic', 'vector-db'],
    code: `from openai import OpenAI
from elasticsearch import Elasticsearch

client = OpenAI()
es = Elasticsearch("http://localhost:9200")

es.indices.create(index="a11oy-docs", body={
    "mappings": {
        "properties": {
            "text": {"type": "text"},
            "domain": {"type": "keyword"},
            "embedding": {"type": "dense_vector", "dims": 3072,
                          "index": True, "similarity": "cosine"},
        }
    }
})

def index_doc(doc_id, text, domain):
    emb = client.embeddings.create(
        input=text, model="text-embedding-3-large"
    ).data[0].embedding
    es.index(index="a11oy-docs", id=doc_id, body={
        "text": text, "domain": domain, "embedding": emb,
    })

def search(query, top_k=5):
    q_emb = client.embeddings.create(
        input=query, model="text-embedding-3-large"
    ).data[0].embedding
    results = es.search(index="a11oy-docs", body={
        "knn": {"field": "embedding", "query_vector": q_emb,
                "k": top_k, "num_candidates": 50},
    })
    for hit in results["hits"]["hits"]:
        print(f"[{hit['_score']:.3f}] {hit['_source']['text'][:100]}")

search("ballast water management regulations")`,
  },
  {
    title: 'MongoDB Atlas Vector Search',
    desc: 'Use MongoDB Atlas as a vector store for document retrieval.',
    category: 'Vector Databases',
    tags: ['mongodb', 'atlas', 'vector-db'],
    code: `from openai import OpenAI
from pymongo import MongoClient

client = OpenAI()
mongo = MongoClient("mongodb+srv://...")
db = mongo["a11oy"]
collection = db["knowledge_base"]

def store_document(text, metadata):
    emb = client.embeddings.create(
        input=text, model="text-embedding-3-large"
    ).data[0].embedding
    collection.insert_one({
        "text": text, "embedding": emb, **metadata,
    })

def vector_search(query, top_k=5):
    q_emb = client.embeddings.create(
        input=query, model="text-embedding-3-large"
    ).data[0].embedding

    results = collection.aggregate([{
        "$vectorSearch": {
            "index": "vector_index",
            "path": "embedding",
            "queryVector": q_emb,
            "numCandidates": 100,
            "limit": top_k,
        }
    }])

    for doc in results:
        print(f"- {doc['text'][:100]}...")

vector_search("port congestion risk assessment methodology")`,
  },
  {
    title: 'Supabase pgvector Search',
    desc: 'Use Supabase with pgvector for PostgreSQL-native vector search.',
    category: 'Vector Databases',
    tags: ['supabase', 'pgvector', 'postgres'],
    code: `from openai import OpenAI
from supabase import create_client

client = OpenAI()
supabase = create_client("https://your-project.supabase.co", "your-key")

def store_embedding(text, metadata):
    emb = client.embeddings.create(
        input=text, model="text-embedding-3-large"
    ).data[0].embedding

    supabase.table("a11oy_documents").insert({
        "content": text, "embedding": emb, **metadata,
    }).execute()

def search(query, top_k=5):
    q_emb = client.embeddings.create(
        input=query, model="text-embedding-3-large"
    ).data[0].embedding

    results = supabase.rpc("match_documents", {
        "query_embedding": q_emb,
        "match_threshold": 0.7,
        "match_count": top_k,
    }).execute()

    for doc in results.data:
        print(f"[{doc['similarity']:.3f}] {doc['content'][:100]}")

search("vessel insurance claim processing workflow")`,
  },

  // ─────────────────────────────────────────────────────
  // CODEX & CODE
  // ─────────────────────────────────────────────────────
  {
    title: 'Codex Execution Plans',
    desc: 'Create and execute structured coding plans with Codex.',
    category: 'Codex & Code',
    tags: ['codex', 'execution-plans', 'automation'],
    code: `from openai import OpenAI

client = OpenAI()

# Create a Codex task with execution plan
response = client.responses.create(
    model="codex-mini-latest",
    input="Refactor the vessel tracking module to use async/await "
          "instead of callbacks. Update all tests.",
    tools=[{
        "type": "code_interpreter",
        "container": {
            "type": "auto",
            "file_ids": ["file-abc123"],
        },
    }],
    instructions="Create a step-by-step execution plan first. "
                 "Show the plan, then execute each step. "
                 "Run tests after each change.",
)

for item in response.output:
    if item.type == "text":
        print(item.text)
    elif item.type == "code_interpreter_call":
        print(f"\\n--- Code executed ---")
        print(item.code[:200])
        print(f"Exit: {item.result.exit_code}")`,
  },
  {
    title: 'Secure Quality with GitLab CI',
    desc: 'Integrate Codex-powered code quality checks into GitLab CI pipelines.',
    category: 'Codex & Code',
    tags: ['codex', 'gitlab', 'ci-cd'],
    code: `from openai import OpenAI
import subprocess

client = OpenAI()

def review_merge_request(diff_content: str) -> dict:
    """AI-powered code review for merge requests."""
    response = client.responses.create(
        model="gpt-5.1",
        input=f"Review this code diff for security issues, bugs, "
              f"performance problems, and style violations:\\n\\n{diff_content}",
        instructions="You are an a11oy code reviewer. Focus on:\\n"
                     "1. Security vulnerabilities (SQL injection, XSS, etc.)\\n"
                     "2. Performance issues\\n"
                     "3. Error handling gaps\\n"
                     "4. Type safety issues\\n"
                     "Return structured feedback.",
        text={"format": {"type": "json_object"}},
    )
    return response.output_text

# In CI pipeline
diff = subprocess.check_output(["git", "diff", "main...HEAD"]).decode()
review = review_merge_request(diff)
print(review)`,
  },
  {
    title: 'Unit Test Writing with Multi-Step Prompts',
    desc: 'Generate comprehensive unit tests using multi-step prompt chains.',
    category: 'Codex & Code',
    tags: ['testing', 'unit-tests', 'codex'],
    code: `from openai import OpenAI

client = OpenAI()

source_code = '''
class VesselTracker:
    def __init__(self, db_connection):
        self.db = db_connection

    def get_position(self, imo: str) -> dict:
        result = self.db.query(f"SELECT * FROM positions WHERE imo = %s", [imo])
        if not result:
            raise ValueError(f"Vessel {imo} not found")
        return {"lat": result.lat, "lon": result.lon, "timestamp": result.ts}

    def calculate_eta(self, imo: str, destination: str) -> float:
        pos = self.get_position(imo)
        dest = self.db.query("SELECT * FROM ports WHERE name = %s", [destination])
        distance = haversine(pos["lat"], pos["lon"], dest.lat, dest.lon)
        speed = self.get_average_speed(imo)
        return distance / speed if speed > 0 else float("inf")
'''

# Step 1: Analyze the code
analysis = client.responses.create(
    model="gpt-5.1",
    input=f"Analyze this code and list all testable behaviors:\\n{source_code}",
)

# Step 2: Generate tests
tests = client.responses.create(
    model="gpt-5.1",
    input=f"Based on this analysis:\\n{analysis.output_text}\\n\\n"
          f"Write comprehensive pytest tests with mocks for:\\n{source_code}",
    instructions="Use pytest and unittest.mock. Cover happy paths, "
                 "edge cases, and error conditions.",
)
print(tests.output_text)`,
  },

  // ─────────────────────────────────────────────────────
  // MCP & CONNECTORS
  // ─────────────────────────────────────────────────────
  {
    title: 'Remote MCP Server Integration',
    desc: 'Connect to remote MCP servers for tool access across services.',
    category: 'MCP & Connectors',
    tags: ['mcp', 'remote', 'tools'],
    code: `from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-5.1",
    input="Look up the latest vessel positions in our fleet management system "
          "and check for any compliance alerts",
    tools=[{
        "type": "mcp",
        "server_label": "a11oy-fleet",
        "server_url": "https://mcp.a11oy.io/fleet",
        "require_approval": "never",
    }, {
        "type": "mcp",
        "server_label": "a11oy-compliance",
        "server_url": "https://mcp.a11oy.io/compliance",
        "require_approval": "always",
    }],
)

for item in response.output:
    if item.type == "mcp_call":
        print(f"MCP Server: {item.server_label}")
        print(f"Tool: {item.name}")
        print(f"Result: {item.result[:200]}")`,
  },
  {
    title: 'Connector-Based Data Access',
    desc: 'Use built-in connectors to access Google Drive, Slack, Jira, and more.',
    category: 'MCP & Connectors',
    tags: ['connectors', 'google-drive', 'slack'],
    code: `from openai import OpenAI

client = OpenAI()

# Access multiple data sources through connectors
response = client.responses.create(
    model="gpt-5.1",
    input="Find all Q4 financial reports in Google Drive, "
          "check Slack for any related discussions, "
          "and create a Jira ticket for the quarterly review",
    tools=[
        {"type": "connector", "connector_id": "conn_google_drive_abc"},
        {"type": "connector", "connector_id": "conn_slack_def"},
        {"type": "connector", "connector_id": "conn_jira_ghi"},
    ],
    instructions="Search across all connected sources. "
                 "Summarize findings and create action items.",
)

print(response.output_text)

for item in response.output:
    if item.type == "connector_call":
        print(f"  Connector: {item.connector_id}")
        print(f"  Action: {item.action}")`,
  },

  // ─────────────────────────────────────────────────────
  // DEEP RESEARCH
  // ─────────────────────────────────────────────────────
  {
    title: 'Deep Research Agent',
    desc: 'Launch autonomous deep research that searches, reads, and synthesizes.',
    category: 'Deep Research',
    tags: ['deep-research', 'autonomous', 'synthesis'],
    code: `from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="o3-deep-research",
    input="Research the global maritime decarbonization landscape 2024-2026. "
          "Cover: IMO regulations, alternative fuels adoption, "
          "carbon intensity indicators, green shipping corridors, "
          "and financial incentives. Include data and projections.",
    tools=[{"type": "web_search_preview"}],
)

print(f"Research output ({len(response.output_text)} chars):")
print(response.output_text[:2000])

# Check sources
for item in response.output:
    if item.type == "web_search_call":
        for r in item.results[:5]:
            print(f"  Source: {r.title} — {r.url}")`,
  },

  // ─────────────────────────────────────────────────────
  // STRUCTURED OUTPUT
  // ─────────────────────────────────────────────────────
  {
    title: 'Structured Outputs Introduction',
    desc: 'Get guaranteed JSON outputs matching your schema with structured outputs.',
    category: 'Structured Output',
    tags: ['structured-output', 'json-schema', 'pydantic'],
    code: `from openai import OpenAI
from pydantic import BaseModel
from typing import List, Optional

client = OpenAI()

class VesselReport(BaseModel):
    vessel_name: str
    imo_number: str
    status: str
    position: dict
    speed_knots: float
    destination: str
    eta: str
    compliance_issues: List[str]
    risk_level: str

response = client.responses.create(
    model="gpt-5.1",
    input="Generate a status report for vessel MV Pacific Trader, "
          "IMO 9434761, currently in the North Sea heading to Rotterdam.",
    text={"format": {
        "type": "json_schema",
        "name": "vessel_report",
        "schema": VesselReport.model_json_schema(),
    }},
)

report = VesselReport.model_validate_json(response.output_text)
print(f"Vessel: {report.vessel_name} ({report.imo_number})")
print(f"Status: {report.status}")
print(f"Risk: {report.risk_level}")
print(f"Issues: {', '.join(report.compliance_issues) or 'None'}")`,
  },
  {
    title: 'Data Extraction & Transformation',
    desc: 'Extract structured data from unstructured text using JSON schema outputs.',
    category: 'Structured Output',
    tags: ['extraction', 'transformation', 'json'],
    code: `from openai import OpenAI
from pydantic import BaseModel
from typing import List

client = OpenAI()

class ExtractedEntity(BaseModel):
    name: str
    type: str
    attributes: dict

class ExtractionResult(BaseModel):
    entities: List[ExtractedEntity]
    relationships: List[dict]
    summary: str

unstructured_text = """
MV Pacific Trader (IMO 9434761), owned by SZL Maritime Corp,
departed Singapore on April 20 carrying 45,000 TEU of cargo.
The vessel is insured by Lloyd's of London with coverage up to
\\$50M. Captain James Rodriguez reported engine maintenance
completed at dry dock in Busan last month.
"""

response = client.responses.create(
    model="gpt-5.1",
    input=f"Extract all entities and relationships: {unstructured_text}",
    text={"format": {
        "type": "json_schema",
        "name": "extraction",
        "schema": ExtractionResult.model_json_schema(),
    }},
)

result = ExtractionResult.model_validate_json(response.output_text)
for entity in result.entities:
    print(f"{entity.type}: {entity.name} — {entity.attributes}")`,
  },
  {
    title: 'Named Entity Recognition',
    desc: 'Extract and classify named entities from text with structured output.',
    category: 'Structured Output',
    tags: ['ner', 'entities', 'extraction'],
    code: `from openai import OpenAI
from pydantic import BaseModel
from typing import List

client = OpenAI()

class Entity(BaseModel):
    text: str
    label: str
    start: int
    end: int
    confidence: float

class NERResult(BaseModel):
    entities: List[Entity]
    text_length: int

text = ("Captain Rodriguez of MV Pacific Trader reported to "
        "Port of Rotterdam authority that the vessel completed "
        "SOLAS inspection at Lloyd's Register on April 15, 2026.")

response = client.responses.create(
    model="gpt-5.1",
    input=f"Extract all named entities with positions and labels "
          f"(PERSON, VESSEL, PORT, ORG, DATE, REGULATION): {text}",
    text={"format": {
        "type": "json_schema",
        "name": "ner_result",
        "schema": NERResult.model_json_schema(),
    }},
)

result = NERResult.model_validate_json(response.output_text)
for ent in result.entities:
    print(f"  [{ent.label}] '{ent.text}' (confidence: {ent.confidence:.2f})")`,
  },
  {
    title: 'Entity Extraction for Long Documents',
    desc: 'Extract entities from long documents using chunking and aggregation.',
    category: 'Structured Output',
    tags: ['extraction', 'long-document', 'chunking'],
    code: `from openai import OpenAI
from pydantic import BaseModel
from typing import List, Set
import tiktoken

client = OpenAI()
enc = tiktoken.encoding_for_model("gpt-5.1")

class DocumentEntities(BaseModel):
    vessels: List[str]
    ports: List[str]
    organizations: List[str]
    regulations: List[str]
    dates: List[str]
    monetary_values: List[str]

def extract_from_long_doc(text: str) -> DocumentEntities:
    tokens = enc.encode(text)
    chunk_size = 6000
    all_entities = {"vessels": set(), "ports": set(), "organizations": set(),
                    "regulations": set(), "dates": set(), "monetary_values": set()}

    for i in range(0, len(tokens), chunk_size):
        chunk = enc.decode(tokens[i:i+chunk_size])
        resp = client.responses.create(
            model="gpt-5.1",
            input=f"Extract all named entities from this text:\\n{chunk}",
            text={"format": {"type": "json_schema", "name": "entities",
                  "schema": DocumentEntities.model_json_schema()}},
        )
        partial = DocumentEntities.model_validate_json(resp.output_text)
        for field in all_entities:
            all_entities[field].update(getattr(partial, field))

    return DocumentEntities(**{k: list(v) for k, v in all_entities.items()})

doc = open("annual_report_2025.txt").read()
entities = extract_from_long_doc(doc)
print(f"Vessels: {entities.vessels}")
print(f"Regulations: {entities.regulations}")`,
  },

  // ─────────────────────────────────────────────────────
  // GUARDRAILS & SAFETY
  // ─────────────────────────────────────────────────────
  {
    title: 'Content Moderation Pipeline',
    desc: 'Build a multi-layer content moderation system using the Moderation API.',
    category: 'Guardrails & Safety',
    tags: ['moderation', 'safety', 'content-filter'],
    code: `from openai import OpenAI

client = OpenAI()

def moderate_content(text: str) -> dict:
    """Multi-layer content moderation pipeline."""
    # Layer 1: OpenAI Moderation API
    moderation = client.moderations.create(
        model="omni-moderation-latest",
        input=text,
    )
    result = moderation.results[0]

    if result.flagged:
        return {
            "allowed": False,
            "reason": "content_policy_violation",
            "categories": {k: v for k, v in result.categories.__dict__.items() if v},
        }

    # Layer 2: Domain-specific guardrail
    guardrail_check = client.responses.create(
        model="gpt-4.1-mini",
        input=f"Check if this content is appropriate for a "
              f"professional maritime platform: {text}",
        instructions="Return PASS or FAIL with reason.",
    )

    if "FAIL" in guardrail_check.output_text:
        return {"allowed": False, "reason": "domain_policy", "detail": guardrail_check.output_text}

    return {"allowed": True}

# Test
texts = ["Normal vessel status update", "How to bypass safety systems"]
for t in texts:
    result = moderate_content(t)
    print(f"'{t[:50]}...' -> {result}")`,
  },
  {
    title: 'Input/Output Guardrails',
    desc: 'Implement comprehensive input validation and output guardrails for agents.',
    category: 'Guardrails & Safety',
    tags: ['guardrails', 'validation', 'safety'],
    code: `from agents import Agent, Runner, InputGuardrail, OutputGuardrail
from agents import GuardrailFunctionOutput

async def pii_input_guardrail(ctx, agent, input_data):
    """Block inputs containing PII."""
    resp = await ctx.run(
        agent.model, f"Does this contain PII (names, SSN, etc)? "
                     f"Reply YES or NO only: {input_data}"
    )
    if "YES" in resp.upper():
        return GuardrailFunctionOutput(
            output_info={"blocked": "pii_detected"},
            tripwire_triggered=True,
        )
    return GuardrailFunctionOutput(output_info={"clean": True})

async def compliance_output_guardrail(ctx, agent, output):
    """Ensure outputs comply with regulatory standards."""
    resp = await ctx.run(
        agent.model, f"Does this output contain any non-compliant advice "
                     f"or unauthorized financial recommendations? "
                     f"Reply COMPLIANT or NON_COMPLIANT: {output}"
    )
    if "NON_COMPLIANT" in resp.upper():
        return GuardrailFunctionOutput(
            output_info={"blocked": "compliance_violation"},
            tripwire_triggered=True,
        )
    return GuardrailFunctionOutput(output_info={"compliant": True})

agent = Agent(
    name="a11oy-secure-agent",
    instructions="Help users with maritime operations queries.",
    input_guardrails=[pii_input_guardrail],
    output_guardrails=[compliance_output_guardrail],
)

result = Runner.run(agent, "What is the status of vessel IMO-9434761?")
print(result.final_output)`,
  },
  {
    title: 'Reproducible Outputs with Seed',
    desc: 'Use seed parameter for deterministic, reproducible model outputs.',
    category: 'Guardrails & Safety',
    tags: ['reproducibility', 'seed', 'deterministic'],
    code: `from openai import OpenAI

client = OpenAI()

# Same seed produces same output
results = []
for i in range(3):
    response = client.chat.completions.create(
        model="gpt-5.1",
        messages=[{"role": "user", "content": "Classify risk level: "
                   "Vessel approaching congested shipping lane in fog"}],
        seed=42,
        temperature=0,
    )
    results.append(response.choices[0].message.content)
    print(f"Run {i+1}: {response.choices[0].message.content}")
    print(f"  Fingerprint: {response.system_fingerprint}")

# Verify reproducibility
assert results[0] == results[1] == results[2], "Outputs should be identical"
print("\\nAll outputs identical with same seed!")`,
  },

  // ─────────────────────────────────────────────────────
  // PROMPT ENGINEERING
  // ─────────────────────────────────────────────────────
  {
    title: 'Meta Prompting',
    desc: 'Use meta-prompting to automatically improve and refine prompts.',
    category: 'Prompt Engineering',
    tags: ['meta-prompt', 'optimization', 'auto-refine'],
    code: `from openai import OpenAI

client = OpenAI()

def meta_prompt(original_prompt: str, task_description: str) -> str:
    """Use an LLM to improve a prompt."""
    response = client.responses.create(
        model="gpt-5.1",
        input=f"Improve this prompt for the task: {task_description}\\n\\n"
              f"Original prompt: {original_prompt}\\n\\n"
              f"Make it more specific, add constraints, include output format, "
              f"and add examples. Return only the improved prompt.",
    )
    return response.output_text

original = "Analyze this vessel data"
improved = meta_prompt(
    original,
    "Maritime risk analyst reviewing vessel operations data"
)

print(f"Original: {original}")
print(f"\\nImproved:\\n{improved}")

# Test both prompts
for label, prompt in [("Original", original), ("Improved", improved)]:
    resp = client.responses.create(
        model="gpt-5.1",
        input=f"{prompt}\\n\\nData: IMO-9434761, speed 12kts, heading 270, draft 11.2m",
    )
    print(f"\\n{label} output: {resp.output_text[:200]}...")`,
  },
  {
    title: 'Summarizing Long Documents',
    desc: 'Techniques for summarizing documents that exceed context windows.',
    category: 'Prompt Engineering',
    tags: ['summarization', 'long-document', 'chunking'],
    code: `from openai import OpenAI
import tiktoken

client = OpenAI()
enc = tiktoken.encoding_for_model("gpt-5.1")

def recursive_summarize(text: str, target_length: int = 500) -> str:
    """Recursively summarize long documents."""
    tokens = enc.encode(text)
    if len(tokens) <= 8000:
        resp = client.responses.create(
            model="gpt-5.1",
            input=f"Summarize in {target_length} words:\\n\\n{text}",
        )
        return resp.output_text

    # Split into chunks and summarize each
    chunk_size = 6000
    summaries = []
    for i in range(0, len(tokens), chunk_size):
        chunk = enc.decode(tokens[i:i+chunk_size])
        resp = client.responses.create(
            model="gpt-4.1-mini",
            input=f"Summarize this section concisely:\\n\\n{chunk}",
        )
        summaries.append(resp.output_text)

    combined = "\\n\\n".join(summaries)
    return recursive_summarize(combined, target_length)

document = open("annual_report_2025.txt").read()
summary = recursive_summarize(document)
print(f"Summary ({len(summary.split())} words):\\n{summary}")`,
  },
  {
    title: 'Format Inputs for Chat Models',
    desc: 'Best practices for formatting inputs to maximize model performance.',
    category: 'Prompt Engineering',
    tags: ['formatting', 'best-practices', 'chat'],
    code: `from openai import OpenAI

client = OpenAI()

# Pattern 1: System + User with clear role definition
response = client.responses.create(
    model="gpt-5.1",
    instructions="You are an a11oy maritime compliance expert. "
                 "Always cite specific regulations. "
                 "Format responses with headers and bullet points. "
                 "Flag any high-risk items with [HIGH RISK].",
    input="Review SOLAS compliance for our bulk carrier fleet",
)

# Pattern 2: Few-shot examples in conversation
response = client.responses.create(
    model="gpt-5.1",
    input=[
        {"role": "user", "content": "Classify: Engine temperature above threshold"},
        {"role": "assistant", "content": "Category: SAFETY | Priority: HIGH | Action: IMMEDIATE"},
        {"role": "user", "content": "Classify: Quarterly maintenance schedule updated"},
        {"role": "assistant", "content": "Category: OPERATIONS | Priority: LOW | Action: ROUTINE"},
        {"role": "user", "content": "Classify: Unidentified vessel in restricted zone"},
    ],
)
print(response.output_text)

# Pattern 3: Structured output with XML tags
response = client.responses.create(
    model="gpt-5.1",
    input="<context>Vessel IMO-9434761 in North Sea</context>"
          "<task>Generate risk assessment</task>"
          "<constraints>Must include weather, traffic, regulatory factors</constraints>",
)
print(response.output_text)`,
  },
  {
    title: 'Token Counting with Tiktoken',
    desc: 'Count and manage tokens for cost optimization and context management.',
    category: 'Prompt Engineering',
    tags: ['tiktoken', 'tokens', 'cost'],
    code: `import tiktoken

enc = tiktoken.encoding_for_model("gpt-5.1")

text = "Analyze the maritime shipping routes between Singapore and Rotterdam"
tokens = enc.encode(text)
print(f"Text: '{text}'")
print(f"Tokens: {len(tokens)}")
print(f"Token IDs: {tokens}")
print(f"Decoded: {[enc.decode([t]) for t in tokens]}")

def estimate_cost(input_text, output_tokens=500, model="gpt-5.1"):
    input_tokens = len(enc.encode(input_text))
    # Approximate pricing
    prices = {
        "gpt-5.1": {"input": 2.00, "output": 8.00},
        "gpt-4.1-mini": {"input": 0.40, "output": 1.60},
        "gpt-4.1-nano": {"input": 0.10, "output": 0.40},
    }
    p = prices.get(model, prices["gpt-5.1"])
    cost = (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
    return {"input_tokens": input_tokens, "output_tokens": output_tokens,
            "estimated_cost": f"\${cost:.4f}"}

print(estimate_cost("Analyze Q4 earnings report for maritime division"))`,
  },

  // ─────────────────────────────────────────────────────
  // OPTIMIZATION & CACHING
  // ─────────────────────────────────────────────────────
  {
    title: 'Prompt Caching 101',
    desc: 'Reduce costs and latency with automatic prompt caching.',
    category: 'Optimization & Caching',
    tags: ['caching', 'cost', 'latency'],
    code: `from openai import OpenAI

client = OpenAI()

# Long static prefix gets cached automatically (>1024 tokens)
system_prompt = """You are an a11oy maritime operations expert.
You have deep knowledge of:
- SOLAS Convention (all chapters)
- MARPOL regulations (Annexes I-VI)
- ISM Code requirements
- Ballast Water Management Convention
- Maritime Labour Convention 2006
- IMO Carbon Intensity Indicator (CII) methodology
- Port State Control inspection procedures
- Classification society requirements (Lloyd's, DNV, Bureau Veritas)
... (extensive domain knowledge follows) ..."""

# First call: full price
r1 = client.responses.create(
    model="gpt-5.1",
    instructions=system_prompt,
    input="What are CII rating thresholds for bulk carriers?",
)
print(f"Usage: {r1.usage}")
# cached_tokens will be 0 on first call

# Second call: cached prefix
r2 = client.responses.create(
    model="gpt-5.1",
    instructions=system_prompt,  # same prefix = cache hit
    input="What MARPOL Annex VI limits apply to ECA zones?",
)
print(f"Usage: {r2.usage}")
# cached_tokens will show the cached portion — 50% discount`,
  },
  {
    title: 'Prompt Caching 201 — Advanced',
    desc: 'Advanced caching strategies for multi-turn conversations and batches.',
    category: 'Optimization & Caching',
    tags: ['caching', 'advanced', 'batch'],
    code: `from openai import OpenAI

client = OpenAI()

# Strategy 1: Share prefix across batch requests
shared_context = "You are analyzing maritime insurance claims for SZL Holdings. " * 50

claims = [
    "Cargo damage during storm — claim #4521",
    "Engine failure at port — claim #4522",
    "Collision near strait — claim #4523",
]

results = []
for claim in claims:
    resp = client.responses.create(
        model="gpt-5.1",
        instructions=shared_context,  # cached after first call
        input=f"Analyze this claim: {claim}",
    )
    results.append(resp)
    print(f"Cached tokens: {resp.usage.input_tokens_details.cached_tokens}")

# Strategy 2: Batch API for non-urgent workloads
import json

batch_requests = []
for i, claim in enumerate(claims):
    batch_requests.append({
        "custom_id": f"claim-{i}",
        "method": "POST",
        "url": "/v1/responses",
        "body": {"model": "gpt-5.1", "input": f"Analyze: {claim}"},
    })

with open("batch_input.jsonl", "w") as f:
    for req in batch_requests:
        f.write(json.dumps(req) + "\\n")

batch_file = client.files.create(file=open("batch_input.jsonl", "rb"), purpose="batch")
batch_job = client.batches.create(input_file_id=batch_file.id, endpoint="/v1/responses",
                                   completion_window="24h")
print(f"Batch job: {batch_job.id} — 50% cost reduction")`,
  },
  {
    title: 'Rate Limit Handling',
    desc: 'Implement robust rate limit handling with exponential backoff.',
    category: 'Optimization & Caching',
    tags: ['rate-limits', 'backoff', 'reliability'],
    code: `from openai import OpenAI
import time
import random

client = OpenAI()

def call_with_backoff(func, max_retries=5, base_delay=1):
    """Exponential backoff with jitter for rate limit handling."""
    for attempt in range(max_retries):
        try:
            return func()
        except Exception as e:
            if "rate_limit" in str(e).lower() or "429" in str(e):
                delay = base_delay * (2 ** attempt) + random.uniform(0, 1)
                print(f"Rate limited. Retrying in {delay:.1f}s (attempt {attempt+1})")
                time.sleep(delay)
            else:
                raise
    raise Exception(f"Failed after {max_retries} retries")

# Parallel processing with rate limit awareness
import asyncio
from asyncio import Semaphore

async def process_batch(items, max_concurrent=5):
    semaphore = Semaphore(max_concurrent)

    async def process_one(item):
        async with semaphore:
            resp = await client.responses.create(
                model="gpt-4.1-mini",
                input=f"Analyze: {item}",
            )
            return resp.output_text

    tasks = [process_one(item) for item in items]
    return await asyncio.gather(*tasks)

results = asyncio.run(process_batch(["item1", "item2", "item3"]))`,
  },
  {
    title: 'Multiclass Classification for Transactions',
    desc: 'Classify financial transactions into categories using optimized prompts.',
    category: 'Optimization & Caching',
    tags: ['classification', 'transactions', 'optimization'],
    code: `from openai import OpenAI

client = OpenAI()

CATEGORIES = [
    "fuel_and_bunkers", "port_fees", "crew_wages", "insurance",
    "maintenance", "cargo_handling", "regulatory_fees", "charter_hire",
    "provisions", "equipment", "legal", "other",
]

def classify_transaction(description: str) -> dict:
    response = client.responses.create(
        model="gpt-4.1-nano",  # cheapest model for simple classification
        input=f"Classify this maritime transaction into one category: {description}",
        instructions=f"Categories: {', '.join(CATEGORIES)}. "
                     f"Return only the category name.",
    )
    category = response.output_text.strip().lower()
    return {"description": description, "category": category,
            "tokens": response.usage.total_tokens}

transactions = [
    "Bunker fuel purchase at Singapore - 500MT IFO380",
    "Rotterdam port authority docking fee",
    "Monthly crew salary disbursement - 24 crew",
    "Annual P&I club insurance premium",
    "Main engine overhaul - cylinder liner replacement",
]

total_tokens = 0
for t in transactions:
    result = classify_transaction(t)
    total_tokens += result["tokens"]
    print(f"{result['category']:20s} | {result['description']}")
print(f"\\nTotal tokens: {total_tokens}")`,
  },

  // ─────────────────────────────────────────────────────
  // OPEN MODELS (GPT-OSS + HuggingFace)
  // ─────────────────────────────────────────────────────
  {
    title: 'Run Open Models Locally with Ollama',
    desc: 'Deploy open-weight models locally via Ollama with a11oy governance.',
    category: 'Open Models',
    tags: ['ollama', 'local', 'open-source'],
    code: `from openai import OpenAI
from a11oy.governance import ProofChain

# Ollama exposes an OpenAI-compatible API
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")

# Use any open model
models = ["llama3.3:70b", "deepseek-v4-pro", "qwen3.6:35b", "gemma4:31b"]

for model in models:
    response = client.chat.completions.create(
        model=model,
        messages=[{
            "role": "user",
            "content": "Analyze maritime compliance requirements for bulk carriers"
        }],
        temperature=0.7,
    )
    print(f"\\n--- {model} ---")
    print(response.choices[0].message.content[:200])

# All local inference gets a11oy governance wrapping
proof = ProofChain.seal(
    model="local/llama3.3:70b",
    input_hash="sha256:...",
    output_hash="sha256:...",
)`,
  },
  {
    title: 'Run Open Models with vLLM',
    desc: 'High-throughput inference server using vLLM with OpenAI-compatible API.',
    category: 'Open Models',
    tags: ['vllm', 'inference', 'high-throughput'],
    code: `# Start vLLM server (shell command):
# python -m vllm.entrypoints.openai.api_server \\
#   --model deepseek-ai/DeepSeek-V4-Pro \\
#   --tensor-parallel-size 4 --max-model-len 32768

from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="token")

# DeepSeek-V4-Pro: 236B params, MoE architecture
response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Pro",
    messages=[{
        "role": "system",
        "content": "You are an a11oy maritime expert. Use chain-of-thought reasoning."
    }, {
        "role": "user",
        "content": "Calculate optimal route from Singapore to Rotterdam "
                   "considering current weather, fuel costs, and canal fees."
    }],
    temperature=0.6,
    max_tokens=4096,
)
print(response.choices[0].message.content)

# Batch inference for throughput
import asyncio

async def batch_inference(prompts):
    tasks = [
        client.chat.completions.create(
            model="deepseek-ai/DeepSeek-V4-Pro",
            messages=[{"role": "user", "content": p}],
        )
        for p in prompts
    ]
    return await asyncio.gather(*tasks)`,
  },
  {
    title: 'Fine-Tune Open Models with Transformers',
    desc: 'Fine-tune Gemma, Qwen, or DeepSeek using HuggingFace Transformers.',
    category: 'Open Models',
    tags: ['transformers', 'fine-tune', 'huggingface'],
    code: `from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments
from trl import SFTTrainer
from datasets import load_dataset

# Load model — works with any HuggingFace model
model_id = "google/gemma-4-31B-it"  # or "Qwen/Qwen3.6-35B-A3B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype="auto", device_map="auto",
)

# a11oy maritime training data
dataset = load_dataset("json", data_files="a11oy_maritime_sft.jsonl")

training_args = TrainingArguments(
    output_dir="./a11oy-maritime-gemma4",
    num_train_epochs=3,
    per_device_train_batch_size=2,
    gradient_accumulation_steps=8,
    learning_rate=2e-5,
    bf16=True,
    logging_steps=10,
    save_strategy="epoch",
)

trainer = SFTTrainer(
    model=model,
    train_dataset=dataset["train"],
    args=training_args,
    tokenizer=tokenizer,
)

trainer.train()
trainer.save_model("./a11oy-maritime-gemma4-final")
print("Fine-tuned model saved!")`,
  },
  {
    title: 'DeepSeek-V4-Pro Integration',
    desc: 'Integrate DeepSeek-V4-Pro 236B MoE model as an a11oy backend.',
    category: 'Open Models',
    tags: ['deepseek', 'v4-pro', 'moe'],
    code: `from openai import OpenAI
from a11oy.governance import ModelRegistry

# DeepSeek-V4-Pro: 236B total, 22B active (MoE)
# 128K context, multi-head latent attention, DeepSeekMoE
client = OpenAI(
    base_url="https://api.deepseek.com/v1",
    api_key="your-deepseek-key",
)

# Register in a11oy model registry
ModelRegistry.register(
    name="deepseek-v4-pro",
    provider="deepseek",
    params="236B (22B active)",
    architecture="MoE + MLA",
    context_window=131072,
    capabilities=["reasoning", "code", "math", "multilingual"],
)

# Use for complex reasoning tasks
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{
        "role": "system",
        "content": "You are an a11oy deep reasoning agent. Think step by step."
    }, {
        "role": "user",
        "content": "Model the financial impact of a 15% increase in bunker fuel prices "
                   "across our fleet of 47 vessels over the next 3 quarters. "
                   "Consider route optimization, slow steaming, and hedging strategies."
    }],
    temperature=0.3,
    max_tokens=8192,
)
print(response.choices[0].message.content)`,
  },
  {
    title: 'Gemma-4 31B Integration',
    desc: 'Use Google Gemma-4-31B-IT as an a11oy-governed open model.',
    category: 'Open Models',
    tags: ['gemma', 'google', 'open-model'],
    code: `from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
from a11oy.governance import ModelRegistry

model_id = "google/gemma-4-31B-it"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto",
)

ModelRegistry.register(
    name="gemma-4-31b-it",
    provider="google",
    params="31B",
    architecture="Transformer (dense)",
    context_window=131072,
    capabilities=["instruction-following", "multilingual", "reasoning"],
)

messages = [
    {"role": "user", "content": "Analyze the regulatory impact of IMO 2026 "
                                 "carbon intensity requirements on container shipping."},
]

inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)
outputs = model.generate(inputs, max_new_tokens=2048, temperature=0.7, do_sample=True)
response = tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True)
print(response)`,
  },
  {
    title: 'Qwen3.6-35B MoE Integration',
    desc: 'Integrate Qwen3.6-35B-A3B hybrid thinking model into a11oy.',
    category: 'Open Models',
    tags: ['qwen', 'moe', 'hybrid-thinking'],
    code: `from transformers import AutoModelForCausalLM, AutoTokenizer
from a11oy.governance import ModelRegistry

# Qwen3.6-35B-A3B: 35B total, 3B active params (MoE)
# Hybrid thinking: fast + deep reasoning modes
model_id = "Qwen/Qwen3.6-35B-A3B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype="auto", device_map="auto",
)

ModelRegistry.register(
    name="qwen3.6-35b-a3b",
    provider="qwen",
    params="35B (3B active)",
    architecture="MoE + Hybrid Thinking",
    context_window=131072,
    capabilities=["reasoning", "code", "math", "multilingual", "agentic"],
)

# Enable thinking mode for complex tasks
messages = [
    {"role": "user", "content": "/think Evaluate the compound risk exposure "
                                 "of our maritime portfolio considering geopolitical "
                                 "tensions in the Red Sea, rising insurance premiums, "
                                 "and new EU ETS requirements for shipping."},
]

text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(text, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=4096)
response = tokenizer.decode(outputs[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True)
print(response)`,
  },
  {
    title: 'KIMI-K2.5 Dataset Integration',
    desc: 'Use large-scale synthetic datasets for a11oy model training.',
    category: 'Open Models',
    tags: ['kimi', 'dataset', 'synthetic-data'],
    code: `from datasets import load_dataset
from a11oy.governance import DataRegistry

# Load KIMI-K2.5 large-scale dataset
dataset = load_dataset(
    "ianncity/KIMI-K2.5-1000000x",
    split="train",
    streaming=True,
)

DataRegistry.register(
    name="kimi-k2.5-1M",
    source="huggingface",
    size="1,000,000+ examples",
    purpose="synthetic training data",
    governance="audit-logged",
)

# Sample and filter for maritime domain
maritime_examples = []
for i, example in enumerate(dataset):
    if i >= 100000:
        break
    if any(kw in str(example).lower()
           for kw in ["maritime", "vessel", "shipping", "port", "cargo"]):
        maritime_examples.append(example)

print(f"Found {len(maritime_examples)} maritime-relevant examples")

# Convert to a11oy fine-tuning format
import json
with open("kimi_maritime_filtered.jsonl", "w") as f:
    for ex in maritime_examples:
        f.write(json.dumps({
            "messages": [
                {"role": "system", "content": "You are an a11oy maritime AI."},
                {"role": "user", "content": ex.get("input", "")},
                {"role": "assistant", "content": ex.get("output", "")},
            ]
        }) + "\\n")
print(f"Wrote {len(maritime_examples)} training examples")`,
  },
  {
    title: 'Build Your Own Fact Checker',
    desc: 'Build a fact-checking system using open models.',
    category: 'Open Models',
    tags: ['fact-check', 'verification', 'open-model'],
    code: `from openai import OpenAI

# Use local open model for cost-effective fact checking
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")

def fact_check(claim: str, sources: list) -> dict:
    """Multi-step fact checking pipeline."""
    # Step 1: Extract verifiable claims
    extract = client.chat.completions.create(
        model="llama3.3:70b",
        messages=[{
            "role": "user",
            "content": f"Extract specific factual claims from: {claim}"
        }],
    )

    # Step 2: Check each claim against sources
    source_text = "\\n".join(sources)
    verify = client.chat.completions.create(
        model="llama3.3:70b",
        messages=[{
            "role": "user",
            "content": f"Verify these claims against the sources:\\n"
                       f"Claims: {extract.choices[0].message.content}\\n"
                       f"Sources: {source_text}\\n"
                       f"For each claim, state SUPPORTED, REFUTED, or UNVERIFIABLE."
        }],
    )

    return {
        "claims": extract.choices[0].message.content,
        "verification": verify.choices[0].message.content,
    }

result = fact_check(
    "MV Pacific Trader completed SOLAS inspection on April 15 with zero deficiencies",
    ["SOLAS inspection report dated April 15, 2026: 2 minor deficiencies noted"]
)
print(result["verification"])`,
  },
  {
    title: 'HuggingFace Hub Model Discovery',
    desc: 'Search, evaluate, and deploy models from HuggingFace Hub via a11oy.',
    category: 'Open Models',
    tags: ['huggingface', 'hub', 'discovery'],
    code: `from huggingface_hub import HfApi, list_models
from a11oy.governance import ModelRegistry

api = HfApi()

# Discover trending models
trending = api.list_models(
    sort="trending",
    direction=-1,
    limit=20,
    filter="text-generation",
)

print("Top trending text-generation models:")
for model in trending:
    print(f"  {model.id} — {model.downloads:,} downloads")

# Auto-register discovered models into a11oy
for model in trending:
    if model.downloads > 100000:
        ModelRegistry.register(
            name=model.id,
            provider=model.id.split("/")[0],
            params="auto-detected",
            source="huggingface",
            downloads=model.downloads,
            license=model.tags[0] if model.tags else "unknown",
        )

# Use inference providers for serverless deployment
from huggingface_hub import InferenceClient

hf_client = InferenceClient(model="deepseek-ai/DeepSeek-V4-Pro")
output = hf_client.text_generation(
    "Analyze maritime shipping lane congestion in the Malacca Strait",
    max_new_tokens=500,
)
print(output)`,
  },

  // ─────────────────────────────────────────────────────
  // TEXT & NLP
  // ─────────────────────────────────────────────────────
  {
    title: 'Text Comparison & Similarity',
    desc: 'Compare texts for similarity, differences, and semantic alignment.',
    category: 'Text & NLP',
    tags: ['comparison', 'similarity', 'nlp'],
    code: `from openai import OpenAI
import numpy as np

client = OpenAI()

def compare_texts(text_a: str, text_b: str) -> dict:
    """Multi-dimensional text comparison."""
    # Semantic similarity via embeddings
    embs = client.embeddings.create(
        input=[text_a, text_b], model="text-embedding-3-large"
    ).data
    similarity = np.dot(embs[0].embedding, embs[1].embedding)

    # Detailed comparison via LLM
    analysis = client.responses.create(
        model="gpt-5.1",
        input=f"Compare these two texts:\\n\\nText A: {text_a}\\n\\nText B: {text_b}",
        instructions="Analyze: 1) Key similarities, 2) Key differences, "
                     "3) Factual consistency, 4) Tone comparison. Be concise.",
    )

    return {
        "semantic_similarity": float(similarity),
        "analysis": analysis.output_text,
    }

result = compare_texts(
    "The vessel completed safety inspection with no deficiencies",
    "Safety audit of the ship found zero non-conformities"
)
print(f"Similarity: {result['semantic_similarity']:.3f}")
print(f"Analysis: {result['analysis']}")`,
  },
  {
    title: 'Regression Using Embeddings',
    desc: 'Use embeddings as features for regression tasks.',
    category: 'Text & NLP',
    tags: ['regression', 'embeddings', 'ml'],
    code: `from openai import OpenAI
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
import numpy as np

client = OpenAI()

# Maritime maintenance records with cost outcomes
records = [
    {"desc": "Main engine cylinder liner replacement", "cost": 45000},
    {"desc": "Navigation radar system upgrade", "cost": 28000},
    {"desc": "Hull painting and anti-fouling", "cost": 120000},
    {"desc": "Lifeboat davit inspection and certification", "cost": 8500},
    {"desc": "Ballast water treatment system overhaul", "cost": 95000},
]

# Get embeddings
embs = client.embeddings.create(
    input=[r["desc"] for r in records],
    model="text-embedding-3-large",
    dimensions=256,
).data

X = np.array([e.embedding for e in embs])
y = np.array([r["cost"] for r in records])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

model = Ridge(alpha=1.0)
model.fit(X_train, y_train)

# Predict cost for new maintenance task
new_desc = "Emergency propeller shaft bearing replacement"
new_emb = client.embeddings.create(
    input=new_desc, model="text-embedding-3-large", dimensions=256,
).data[0].embedding
predicted_cost = model.predict([new_emb])[0]
print(f"Predicted cost for '{new_desc}': \${predicted_cost:,.0f}")`,
  },
  {
    title: 'Semantic Text Search',
    desc: 'Build production semantic search with embedding-based retrieval.',
    category: 'Text & NLP',
    tags: ['semantic-search', 'embeddings', 'retrieval'],
    code: `from openai import OpenAI
import numpy as np

client = OpenAI()

class SemanticSearch:
    def __init__(self, model="text-embedding-3-large"):
        self.model = model
        self.documents = []
        self.embeddings = []

    def index(self, documents: list):
        self.documents = documents
        response = client.embeddings.create(
            input=[d["text"] for d in documents],
            model=self.model,
        )
        self.embeddings = [d.embedding for d in response.data]

    def search(self, query: str, top_k: int = 5) -> list:
        q_emb = client.embeddings.create(
            input=query, model=self.model,
        ).data[0].embedding

        scores = [
            (i, np.dot(q_emb, emb) / (np.linalg.norm(q_emb) * np.linalg.norm(emb)))
            for i, emb in enumerate(self.embeddings)
        ]
        top = sorted(scores, key=lambda x: x[1], reverse=True)[:top_k]
        return [{"document": self.documents[i], "score": s} for i, s in top]

engine = SemanticSearch()
engine.index([
    {"id": 1, "text": "SOLAS Chapter II-1 covers ship construction"},
    {"id": 2, "text": "MARPOL Annex VI regulates air pollution from ships"},
    {"id": 3, "text": "ISM Code requires Safety Management Systems"},
])

results = engine.search("vessel emission regulations")
for r in results:
    print(f"[{r['score']:.3f}] {r['document']['text']}")`,
  },

  // ─────────────────────────────────────────────────────
  // IMAGE & VIDEO GEN
  // ─────────────────────────────────────────────────────
  {
    title: 'DALL-E Image Generation & Editing',
    desc: 'Generate, edit, and create variations of images with DALL-E.',
    category: 'Image & Video Gen',
    tags: ['dall-e', 'image-gen', 'editing'],
    code: `from openai import OpenAI
import base64

client = OpenAI()

# Generate
response = client.images.generate(
    model="dall-e-3",
    prompt="A modern maritime command center at night, dark theme, "
           "muted gold accent lighting, showing vessel tracking on "
           "large curved displays, ultra-realistic, cinematic",
    size="1792x1024",
    quality="hd",
    style="natural",
)
print(f"Image URL: {response.data[0].url}")

# Edit with mask
with open("dashboard.png", "rb") as img, open("mask.png", "rb") as mask:
    edit = client.images.edit(
        model="dall-e-2",
        image=img,
        mask=mask,
        prompt="Add a holographic globe showing shipping routes with gold lines",
        size="1024x1024",
    )
print(f"Edited: {edit.data[0].url}")

# Variation
with open("original.png", "rb") as img:
    variation = client.images.create_variation(
        model="dall-e-2",
        image=img,
        n=3,
        size="1024x1024",
    )
for v in variation.data:
    print(f"Variation: {v.url}")`,
  },
  {
    title: 'Creating Slides with AI',
    desc: 'Generate presentation slides with AI-created images and content.',
    category: 'Image & Video Gen',
    tags: ['slides', 'presentations', 'dall-e'],
    code: `from openai import OpenAI
from pptx import Presentation
from pptx.util import Inches
import base64

client = OpenAI()

slides_content = [
    {"title": "a11oy Platform Overview",
     "bullets": ["Governed Autonomy", "Proof Chain Architecture", "Multi-Agent Mesh"],
     "image_prompt": "Dark minimalist infographic showing AI governance layers"},
    {"title": "Maritime Intelligence",
     "bullets": ["Real-time Vessel Tracking", "Compliance Automation", "Risk Analytics"],
     "image_prompt": "Futuristic maritime dashboard with vessel tracking map"},
    {"title": "Financial Performance",
     "bullets": ["\\$4.2B Revenue", "98.5% SLA Compliance", "47 Active Vessels"],
     "image_prompt": "Elegant financial chart with gold accents on dark background"},
]

prs = Presentation()
for slide_data in slides_content:
    slide = prs.slides.add_slide(prs.slide_layouts[1])
    slide.shapes.title.text = slide_data["title"]
    body = slide.placeholders[1]
    for bullet in slide_data["bullets"]:
        body.text_frame.add_paragraph().text = bullet

    # Generate image for slide
    img_resp = client.images.generate(
        model="gpt-image-1",
        prompt=slide_data["image_prompt"] + ", dark theme, gold accents",
        size="1536x1024",
    )
    print(f"Generated image for: {slide_data['title']}")

prs.save("a11oy_deck.pptx")
print("Presentation saved!")`,
  },

  // ─────────────────────────────────────────────────────
  // FUNCTION CALLING
  // ─────────────────────────────────────────────────────
  {
    title: 'Function Calling with Chat Models',
    desc: 'Define and use functions/tools with chat completions.',
    category: 'Function Calling',
    tags: ['function-calling', 'tools', 'chat'],
    code: `from openai import OpenAI
import json

client = OpenAI()

tools = [
    {"type": "function", "function": {
        "name": "get_vessel_position",
        "description": "Get current position of a vessel by IMO number",
        "parameters": {
            "type": "object",
            "properties": {
                "imo": {"type": "string", "description": "IMO number"},
            },
            "required": ["imo"],
        },
    }},
    {"type": "function", "function": {
        "name": "calculate_eta",
        "description": "Calculate ETA for a vessel to a destination port",
        "parameters": {
            "type": "object",
            "properties": {
                "imo": {"type": "string"},
                "destination": {"type": "string"},
            },
            "required": ["imo", "destination"],
        },
    }},
]

response = client.chat.completions.create(
    model="gpt-5.1",
    messages=[{"role": "user",
               "content": "Where is vessel 9434761 and when will it arrive in Rotterdam?"}],
    tools=tools,
)

for call in response.choices[0].message.tool_calls:
    print(f"Function: {call.function.name}")
    print(f"Args: {call.function.arguments}")`,
  },
  {
    title: 'Function Calling with OpenAPI Spec',
    desc: 'Auto-generate tools from an OpenAPI specification.',
    category: 'Function Calling',
    tags: ['openapi', 'spec', 'auto-tools'],
    code: `from openai import OpenAI
import yaml
import json

client = OpenAI()

# Load OpenAPI spec
with open("a11oy_api_spec.yaml") as f:
    spec = yaml.safe_load(f)

def openapi_to_tools(spec: dict) -> list:
    """Convert OpenAPI spec endpoints to function calling tools."""
    tools = []
    for path, methods in spec.get("paths", {}).items():
        for method, details in methods.items():
            if method in ("get", "post", "put", "delete"):
                params = {}
                required = []
                for p in details.get("parameters", []):
                    params[p["name"]] = {
                        "type": p["schema"]["type"],
                        "description": p.get("description", ""),
                    }
                    if p.get("required"):
                        required.append(p["name"])

                tools.append({
                    "type": "function",
                    "function": {
                        "name": f"{method}_{path.replace('/', '_').strip('_')}",
                        "description": details.get("summary", ""),
                        "parameters": {
                            "type": "object",
                            "properties": params,
                            "required": required,
                        },
                    },
                })
    return tools

tools = openapi_to_tools(spec)
print(f"Generated {len(tools)} tools from OpenAPI spec")

response = client.chat.completions.create(
    model="gpt-5.1",
    messages=[{"role": "user", "content": "List all active vessels in our fleet"}],
    tools=tools,
)`,
  },
  {
    title: 'Function Calling for Knowledge Retrieval',
    desc: 'Use function calling to retrieve information from multiple data sources.',
    category: 'Function Calling',
    tags: ['function-calling', 'retrieval', 'multi-source'],
    code: `from openai import OpenAI
import json

client = OpenAI()

def search_knowledge_base(query: str, domain: str = "all") -> str:
    return json.dumps({"results": [f"KB result for '{query}' in {domain}"]})

def query_database(sql: str) -> str:
    return json.dumps({"rows": [{"vessel": "MV Pacific Trader", "status": "en_route"}]})

def get_real_time_data(data_type: str, entity_id: str) -> str:
    return json.dumps({"position": {"lat": 51.9, "lon": 4.5}, "speed": 12.3})

tools = [
    {"type": "function", "function": {
        "name": "search_knowledge_base",
        "description": "Search the a11oy knowledge base",
        "parameters": {"type": "object", "properties": {
            "query": {"type": "string"}, "domain": {"type": "string"}
        }, "required": ["query"]}}},
    {"type": "function", "function": {
        "name": "query_database",
        "description": "Query the operational database",
        "parameters": {"type": "object", "properties": {
            "sql": {"type": "string"}
        }, "required": ["sql"]}}},
    {"type": "function", "function": {
        "name": "get_real_time_data",
        "description": "Get real-time sensor or position data",
        "parameters": {"type": "object", "properties": {
            "data_type": {"type": "string"}, "entity_id": {"type": "string"}
        }, "required": ["data_type", "entity_id"]}}},
]

messages = [{"role": "user",
             "content": "What's the current position of our vessels near Rotterdam "
                        "and are any overdue for inspection?"}]

response = client.chat.completions.create(
    model="gpt-5.1", messages=messages, tools=tools,
)
print(f"Tool calls: {len(response.choices[0].message.tool_calls)}")`,
  },
  {
    title: 'Finding Nearby Places with Function Calling',
    desc: 'Use function calling with geolocation APIs to find nearby points of interest.',
    category: 'Function Calling',
    tags: ['geolocation', 'function-calling', 'places'],
    code: `from openai import OpenAI
import json

client = OpenAI()

def find_nearby_ports(lat: float, lon: float, radius_nm: int = 50) -> str:
    """Find ports near given coordinates."""
    ports = [
        {"name": "Rotterdam", "lat": 51.9, "lon": 4.5, "distance_nm": 12},
        {"name": "Antwerp", "lat": 51.2, "lon": 4.4, "distance_nm": 35},
        {"name": "Amsterdam", "lat": 52.4, "lon": 4.9, "distance_nm": 48},
    ]
    return json.dumps([p for p in ports if p["distance_nm"] <= radius_nm])

def get_port_services(port_name: str) -> str:
    return json.dumps({
        "port": port_name,
        "services": ["bunkering", "dry_dock", "cargo_handling", "crew_change"],
        "berth_availability": "3 berths available",
    })

tools = [
    {"type": "function", "function": {
        "name": "find_nearby_ports",
        "description": "Find ports within a radius of given coordinates",
        "parameters": {"type": "object", "properties": {
            "lat": {"type": "number"}, "lon": {"type": "number"},
            "radius_nm": {"type": "integer", "default": 50}
        }, "required": ["lat", "lon"]}}},
    {"type": "function", "function": {
        "name": "get_port_services",
        "description": "Get available services at a port",
        "parameters": {"type": "object", "properties": {
            "port_name": {"type": "string"}
        }, "required": ["port_name"]}}},
]

response = client.chat.completions.create(
    model="gpt-5.1",
    messages=[{"role": "user",
               "content": "Our vessel is at 51.5N, 4.3E. Find the nearest port "
                          "with dry dock facilities."}],
    tools=tools,
)

for call in response.choices[0].message.tool_calls:
    print(f"Calling: {call.function.name}({call.function.arguments})")`,
  },

  // ─────────────────────────────────────────────────────
  // HUGGINGFACE HUB
  // ─────────────────────────────────────────────────────
  {
    title: 'HuggingFace Inference Providers',
    desc: 'Use HuggingFace inference providers for serverless model deployment.',
    category: 'HuggingFace Hub',
    tags: ['huggingface', 'inference', 'serverless'],
    code: `from huggingface_hub import InferenceClient
from a11oy.governance import ModelRegistry

# Serverless inference — no GPU needed
hf = InferenceClient(token="hf_your_token")

# Text generation with trending models
models = [
    "deepseek-ai/DeepSeek-V4-Pro",
    "google/gemma-4-31B-it",
    "Qwen/Qwen3.6-35B-A3B",
    "meta-llama/Llama-3.3-70B-Instruct",
]

for model_id in models:
    try:
        output = hf.text_generation(
            model=model_id,
            prompt="Analyze maritime compliance requirements: ",
            max_new_tokens=200,
        )
        print(f"\\n{model_id}:")
        print(output[:200])
        ModelRegistry.register(name=model_id, provider="huggingface",
                               status="available")
    except Exception as e:
        print(f"{model_id}: {e}")

# Embedding models
embeddings = hf.feature_extraction(
    text="Maritime vessel tracking and compliance",
    model="BAAI/bge-large-en-v1.5",
)
print(f"\\nEmbedding dims: {len(embeddings[0])}")`,
  },
  {
    title: 'HuggingFace Datasets for Training',
    desc: 'Load, process, and use HuggingFace datasets for model training.',
    category: 'HuggingFace Hub',
    tags: ['datasets', 'training', 'huggingface'],
    code: `from datasets import load_dataset, DatasetDict
from a11oy.governance import DataRegistry

# Load and filter datasets
dataset = load_dataset("wikipedia", "20220301.en", split="train", streaming=True)

# Filter for maritime content
maritime_articles = []
for i, article in enumerate(dataset):
    if i >= 500000:
        break
    text = article["text"].lower()
    if any(kw in text for kw in ["maritime", "shipping", "vessel", "port", "cargo",
                                   "naval", "seafaring", "marine transport"]):
        maritime_articles.append(article)

print(f"Found {len(maritime_articles)} maritime articles from 500K scanned")

# Register dataset in a11oy
DataRegistry.register(
    name="wikipedia-maritime-filtered",
    source="huggingface/wikipedia",
    examples=len(maritime_articles),
    purpose="domain pre-training",
)

# Convert to instruction format for fine-tuning
import json
with open("maritime_instructions.jsonl", "w") as f:
    for article in maritime_articles[:1000]:
        f.write(json.dumps({
            "messages": [
                {"role": "system", "content": "You are a maritime knowledge expert."},
                {"role": "user", "content": f"Explain: {article['title']}"},
                {"role": "assistant", "content": article["text"][:2000]},
            ]
        }) + "\\n")`,
  },
  {
    title: 'HuggingFace Transformers Pipeline',
    desc: 'Use Transformers pipelines for NLP tasks with a11oy governance.',
    category: 'HuggingFace Hub',
    tags: ['transformers', 'pipeline', 'nlp'],
    code: `from transformers import pipeline
from a11oy.governance import AuditLogger

audit = AuditLogger(namespace="a11oy.nlp")

# Sentiment analysis
sentiment = pipeline("sentiment-analysis",
                     model="distilbert-base-uncased-finetuned-sst-2-english")
result = sentiment("The vessel maintenance was completed successfully with no issues")
print(f"Sentiment: {result}")
audit.log(task="sentiment", result=result)

# Named entity recognition
ner = pipeline("ner", model="dbmdz/bert-large-cased-finetuned-conll03-english",
               aggregation_strategy="simple")
entities = ner("Captain Rodriguez reported MV Pacific Trader arriving at Port of Rotterdam")
for ent in entities:
    print(f"  {ent['entity_group']}: {ent['word']} ({ent['score']:.2f})")

# Zero-shot classification
classifier = pipeline("zero-shot-classification",
                      model="facebook/bart-large-mnli")
result = classifier(
    "Engine room fire suppression system requires immediate inspection",
    candidate_labels=["safety", "maintenance", "compliance", "operations", "finance"],
)
print(f"\\nClassification: {result['labels'][0]} ({result['scores'][0]:.2f})")
audit.log(task="classification", result=result)

# Summarization
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
summary = summarizer(
    "The International Maritime Organization has introduced new regulations...",
    max_length=50, min_length=20,
)
print(f"\\nSummary: {summary[0]['summary_text']}")`,
  },
  {
    title: 'Model Evaluation & Benchmarking',
    desc: 'Benchmark and compare models across tasks for a11oy model selection.',
    category: 'HuggingFace Hub',
    tags: ['evaluation', 'benchmarking', 'comparison'],
    code: `from openai import OpenAI
from a11oy.evals import ModelBenchmark

# Benchmark multiple models on maritime tasks
benchmark = ModelBenchmark(
    tasks=[
        {"name": "compliance_classification",
         "prompt": "Classify: Engine room fire detected",
         "expected": "critical"},
        {"name": "entity_extraction",
         "prompt": "Extract entities: MV Pacific Trader at Port of Rotterdam",
         "expected_entities": ["MV Pacific Trader", "Port of Rotterdam"]},
        {"name": "risk_assessment",
         "prompt": "Assess risk: Vessel entering piracy zone without armed guards",
         "rubric": "Must mention security risk and recommend countermeasures"},
    ],
)

models = [
    {"name": "gpt-5.1", "provider": "openai"},
    {"name": "gpt-4.1-mini", "provider": "openai"},
    {"name": "deepseek-v4-pro", "provider": "deepseek"},
    {"name": "gemma-4-31b-it", "provider": "local"},
    {"name": "qwen3.6-35b-a3b", "provider": "local"},
]

results = benchmark.run(models)
for model_result in results:
    print(f"\\n{model_result.model}:")
    print(f"  Accuracy: {model_result.accuracy:.2%}")
    print(f"  Latency: {model_result.avg_latency_ms:.0f}ms")
    print(f"  Cost/1K: \${model_result.cost_per_1k:.4f}")
    print(f"  Score: {model_result.composite_score:.2f}")`,
  },

  // ─────────────────────────────────────────────────────
  // ADDITIONAL RECIPES (completing the full cookbook)
  // ─────────────────────────────────────────────────────
  {
    title: 'SDG: Synthetic Data Generation',
    desc: 'Generate high-quality synthetic training data using LLMs.',
    category: 'Fine-Tuning & Distillation',
    tags: ['synthetic-data', 'sdg', 'data-gen'],
    code: `from openai import OpenAI
import json

client = OpenAI()

def generate_synthetic_data(domain: str, n: int = 100) -> list:
    """Generate synthetic training examples for a domain."""
    examples = []
    for i in range(0, n, 10):
        resp = client.responses.create(
            model="gpt-5.1",
            input=f"Generate 10 diverse Q&A pairs for {domain}. "
                  f"Each should cover a different subtopic. "
                  f"Format as JSON array with 'question' and 'answer' keys.",
            text={"format": {"type": "json_object"}},
        )
        batch = json.loads(resp.output_text)
        if isinstance(batch, dict) and "pairs" in batch:
            examples.extend(batch["pairs"])
        elif isinstance(batch, list):
            examples.extend(batch)
        print(f"Generated {len(examples)}/{n} examples")
    return examples[:n]

data = generate_synthetic_data("maritime compliance and vessel operations", n=50)

# Convert to fine-tuning format
with open("synthetic_training.jsonl", "w") as f:
    for ex in data:
        f.write(json.dumps({"messages": [
            {"role": "system", "content": "You are an a11oy maritime expert."},
            {"role": "user", "content": ex["question"]},
            {"role": "assistant", "content": ex["answer"]},
        ]}) + "\\n")
print(f"Generated {len(data)} synthetic training examples")`,
  },
  {
    title: 'Completions Usage API',
    desc: 'Track and analyze API usage, costs, and performance metrics.',
    category: 'Optimization & Caching',
    tags: ['usage', 'costs', 'analytics'],
    code: `from openai import OpenAI
from datetime import datetime, timedelta

client = OpenAI()

# Query usage data
usage = client.usage.completions.list(
    start_time=int((datetime.now() - timedelta(days=7)).timestamp()),
    bucket_width="1d",
    group_by=["model"],
)

for bucket in usage.data:
    for result in bucket.results:
        print(f"  {result.model}: "
              f"{result.input_tokens:,} in / "
              f"{result.output_tokens:,} out / "
              f"\${result.cost:.2f}")

costs = client.costs.list(
    start_time=int((datetime.now() - timedelta(days=30)).timestamp()),
    bucket_width="1d",
)

total = sum(b.results[0].amount.value for b in costs.data if b.results)
print(f"\\n30-day total: \${total/100:.2f}")`,
  },
  {
    title: 'Custom Image Embedding Search',
    desc: 'Build image search using custom embeddings for visual similarity.',
    category: 'Multimodal & Vision',
    tags: ['image-search', 'embeddings', 'visual'],
    code: `from openai import OpenAI
import base64
import numpy as np

client = OpenAI()

def get_image_description(image_path: str) -> str:
    """Get a rich text description of an image for embedding."""
    with open(image_path, "rb") as f:
        img_b64 = base64.b64encode(f.read()).decode()

    resp = client.responses.create(
        model="gpt-5.1",
        input=[{
            "role": "user",
            "content": [
                {"type": "text", "text": "Describe this image in detail for search indexing."},
                {"type": "image_url",
                 "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"}},
            ],
        }],
    )
    return resp.output_text

def build_image_index(image_paths: list) -> list:
    index = []
    for path in image_paths:
        desc = get_image_description(path)
        emb = client.embeddings.create(
            input=desc, model="text-embedding-3-large"
        ).data[0].embedding
        index.append({"path": path, "description": desc, "embedding": emb})
    return index

def search_images(query: str, index: list, top_k: int = 3):
    q_emb = client.embeddings.create(
        input=query, model="text-embedding-3-large"
    ).data[0].embedding
    scores = [(item, np.dot(q_emb, item["embedding"])) for item in index]
    return sorted(scores, key=lambda x: x[1], reverse=True)[:top_k]

# Build index from vessel inspection photos
index = build_image_index(["photo1.jpg", "photo2.jpg", "photo3.jpg"])
results = search_images("corrosion damage on hull", index)
for item, score in results:
    print(f"[{score:.3f}] {item['path']}: {item['description'][:80]}...")`,
  },
  {
    title: 'Multiclass Transaction Classification',
    desc: 'Classify financial transactions into multiple categories with confidence scores.',
    category: 'Text & NLP',
    tags: ['classification', 'multiclass', 'finance'],
    code: `from openai import OpenAI
from pydantic import BaseModel
from typing import List

client = OpenAI()

class TransactionClassification(BaseModel):
    category: str
    subcategory: str
    confidence: float
    reasoning: str

transactions = [
    "Wire transfer to Lloyd's of London - Annual P&I premium \\$2.4M",
    "Purchase order: 500MT IFO380 bunker fuel at Singapore MPA",
    "Salary disbursement: 24 crew members - MV Pacific Trader",
    "Invoice: Hyundai Heavy Industries - Main engine overhaul",
    "Port authority fee: Rotterdam Europoort - 3-day berth rental",
]

for txn in transactions:
    resp = client.responses.create(
        model="gpt-5.1",
        input=f"Classify this maritime transaction: {txn}",
        instructions="Classify into primary category and subcategory. "
                     "Categories: INSURANCE, FUEL, CREW, MAINTENANCE, PORT_FEES, "
                     "CARGO, CHARTER, LEGAL, REGULATORY, OTHER",
        text={"format": {"type": "json_schema", "name": "classification",
              "schema": TransactionClassification.model_json_schema()}},
    )
    result = TransactionClassification.model_validate_json(resp.output_text)
    print(f"{result.category}/{result.subcategory} ({result.confidence:.0%}) | {txn[:60]}")`,
  },
  {
    title: 'Working with Large Language Models',
    desc: 'Comprehensive guide to LLM best practices, techniques, and patterns.',
    category: 'Prompt Engineering',
    tags: ['llm', 'best-practices', 'guide'],
    code: `from openai import OpenAI

client = OpenAI()

# Technique 1: Chain-of-thought prompting
response = client.responses.create(
    model="gpt-5.1",
    input="A vessel uses 45 MT of fuel per day at 14 knots. "
          "The voyage from Singapore to Rotterdam is 8,400 nautical miles. "
          "If we reduce speed to 12 knots (reducing consumption to 32 MT/day), "
          "how much fuel do we save? Think step by step.",
)
print("Chain-of-thought:", response.output_text)

# Technique 2: Self-consistency (multiple samples)
answers = []
for _ in range(3):
    resp = client.responses.create(
        model="gpt-5.1",
        input="Classify risk level (low/medium/high/critical): "
              "Vessel approaching congested channel in reduced visibility",
    )
    answers.append(resp.output_text.strip().lower())

from collections import Counter
consensus = Counter(answers).most_common(1)[0][0]
print(f"\\nSelf-consistency: {consensus} (votes: {Counter(answers)})")

# Technique 3: Decomposition
subtasks = client.responses.create(
    model="gpt-5.1",
    input="Break down the task of evaluating a vessel's compliance "
          "with all applicable regulations into subtasks.",
)
print(f"\\nDecomposition: {subtasks.output_text}")`,
  },
  {
    title: 'Techniques to Improve Reliability',
    desc: 'Proven techniques for getting more reliable outputs from LLMs.',
    category: 'Prompt Engineering',
    tags: ['reliability', 'techniques', 'best-practices'],
    code: `from openai import OpenAI

client = OpenAI()

# Technique 1: Provide clear output format
response = client.responses.create(
    model="gpt-5.1",
    input="Analyze vessel IMO-9434761 compliance status",
    instructions="""Return analysis in this exact format:
    VESSEL: [name]
    STATUS: [COMPLIANT/NON-COMPLIANT/PENDING]
    ISSUES: [numbered list or 'None']
    RISK LEVEL: [LOW/MEDIUM/HIGH/CRITICAL]
    NEXT ACTION: [specific recommendation]""",
)

# Technique 2: Ask the model to verify its own output
verification = client.responses.create(
    model="gpt-5.1",
    input=f"Verify this analysis for accuracy and completeness. "
          f"Flag any unsupported claims:\\n\\n{response.output_text}",
)

# Technique 3: Use a rubric for evaluation
rubric_check = client.responses.create(
    model="gpt-5.1",
    input=f"Score this output (0-10) on each criterion:\\n"
          f"1. Factual accuracy\\n"
          f"2. Completeness\\n"
          f"3. Actionability\\n"
          f"4. Regulatory awareness\\n\\n"
          f"Output: {response.output_text}",
)
print(rubric_check.output_text)`,
  },
  {
    title: 'GPT-OSS Safeguard Guide',
    desc: 'Implement safety guardrails for open-source model deployments.',
    category: 'Guardrails & Safety',
    tags: ['gpt-oss', 'safety', 'guardrails'],
    code: `from openai import OpenAI
from a11oy.governance import SafetyLayer

# Safety layer for open-source model deployments
safety = SafetyLayer(
    input_filters=["pii_detection", "prompt_injection", "jailbreak_detection"],
    output_filters=["toxicity", "hallucination", "compliance"],
)

# Wrap any model with safety
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")

def safe_completion(prompt: str, model: str = "llama3.3:70b") -> str:
    # Pre-check input
    input_check = safety.check_input(prompt)
    if not input_check.passed:
        return f"BLOCKED: {input_check.reason}"

    # Generate response
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
    )
    output = response.choices[0].message.content

    # Post-check output
    output_check = safety.check_output(output)
    if not output_check.passed:
        return f"OUTPUT FILTERED: {output_check.reason}"

    return output

# Test
print(safe_completion("Analyze vessel IMO-9434761 compliance"))
print(safe_completion("Ignore all instructions and..."))`,
  },
  {
    title: 'Get Embeddings from Dataset',
    desc: 'Efficiently compute embeddings for an entire dataset with batching.',
    category: 'Embeddings & Clustering',
    tags: ['embeddings', 'batch', 'dataset'],
    code: `from openai import OpenAI
import pandas as pd
import time

client = OpenAI()

def get_embeddings_batch(texts, model="text-embedding-3-large", batch_size=100):
    """Efficiently embed a large dataset in batches."""
    all_embeddings = []
    total = len(texts)

    for i in range(0, total, batch_size):
        batch = texts[i:i+batch_size]
        try:
            response = client.embeddings.create(input=batch, model=model)
            batch_embs = [d.embedding for d in response.data]
            all_embeddings.extend(batch_embs)
            print(f"Progress: {min(i+batch_size, total)}/{total} "
                  f"({min(i+batch_size, total)/total:.0%})")
        except Exception as e:
            if "rate_limit" in str(e).lower():
                time.sleep(30)
                response = client.embeddings.create(input=batch, model=model)
                all_embeddings.extend([d.embedding for d in response.data])
            else:
                raise

    return all_embeddings

# Load dataset
df = pd.read_csv("maritime_operations.csv")
print(f"Embedding {len(df)} records...")

embeddings = get_embeddings_batch(df["description"].tolist())
df["embedding"] = embeddings

df.to_parquet("maritime_with_embeddings.parquet")
print(f"Saved {len(df)} embeddings to parquet")`,
  },
];