llmkit 0.1.3

Production-grade LLM client - 100+ providers, 11,000+ models. Pure Rust.
Documentation
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
//! Generic OpenAI-compatible API provider implementation.
//!
//! This module provides a generic provider that works with any OpenAI-compatible API.
//! Many LLM providers use OpenAI's API format, making this a single implementation
//! that covers 15+ providers.
//!
//! # Supported Providers
//!
//! | Provider | Base URL | Env Var |
//! |----------|----------|---------|
//! | Together AI | `https://api.together.xyz/v1` | `TOGETHER_API_KEY` |
//! | Fireworks AI | `https://api.fireworks.ai/inference/v1` | `FIREWORKS_API_KEY` |
//! | DeepSeek | `https://api.deepseek.com/v1` | `DEEPSEEK_API_KEY` |
//! | Perplexity | `https://api.perplexity.ai` | `PERPLEXITY_API_KEY` |
//! | Anyscale | `https://api.endpoints.anyscale.com/v1` | `ANYSCALE_API_KEY` |
//! | DeepInfra | `https://api.deepinfra.com/v1/openai` | `DEEPINFRA_API_KEY` |
//! | Lepton AI | `https://llama3-1-8b.lepton.run/api/v1` | `LEPTON_API_KEY` |
//! | Novita AI | `https://api.novita.ai/v3/openai` | `NOVITA_API_KEY` |
//! | Hyperbolic | `https://api.hyperbolic.xyz/v1` | `HYPERBOLIC_API_KEY` |
//! | Cerebras | `https://api.cerebras.ai/v1` | `CEREBRAS_API_KEY` |
//! | LM Studio | `http://localhost:1234/v1` | - (local) |
//! | vLLM | `http://localhost:8000/v1` | - (local) |
//! | TGI | `http://localhost:8080/v1` | - (local) |
//! | Llamafile | `http://localhost:8080/v1` | - (local) |
//!
//! # Example
//!
//! ```ignore
//! use llmkit::providers::OpenAICompatibleProvider;
//!
//! // Use a known provider
//! let together = OpenAICompatibleProvider::together_from_env()?;
//!
//! // Or a custom OpenAI-compatible endpoint
//! let custom = OpenAICompatibleProvider::custom(
//!     "my-provider",
//!     "https://my-api.example.com/v1",
//!     Some("my-api-key".to_string()),
//! )?;
//! ```

use std::pin::Pin;

use async_trait::async_trait;
use futures::Stream;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::error::{Error, Result};
use crate::provider::{Provider, ProviderConfig};
use crate::types::{
    CompletionRequest, CompletionResponse, ContentBlock, ContentDelta, Message, Role, StopReason,
    StreamChunk, StreamEventType, Usage,
};

/// Known OpenAI-compatible provider configurations.
#[derive(Debug, Clone)]
pub struct ProviderInfo {
    /// Provider name for logging and identification.
    pub name: &'static str,
    /// Base URL for the API (without /chat/completions).
    pub base_url: &'static str,
    /// Environment variable for API key.
    pub env_var: &'static str,
    /// Whether this provider supports tool/function calling.
    pub supports_tools: bool,
    /// Whether this provider supports vision/images.
    pub supports_vision: bool,
    /// Whether this provider supports streaming.
    pub supports_streaming: bool,
    /// Default model for this provider.
    pub default_model: Option<&'static str>,
}

/// Pre-defined provider configurations.
pub mod known_providers {
    use super::ProviderInfo;

    pub const TOGETHER: ProviderInfo = ProviderInfo {
        name: "together",
        base_url: "https://api.together.xyz/v1",
        env_var: "TOGETHER_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"),
    };

    pub const FIREWORKS: ProviderInfo = ProviderInfo {
        name: "fireworks",
        base_url: "https://api.fireworks.ai/inference/v1",
        env_var: "FIREWORKS_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("accounts/fireworks/models/llama-v3p1-70b-instruct"),
    };

    pub const DEEPSEEK: ProviderInfo = ProviderInfo {
        name: "deepseek",
        base_url: "https://api.deepseek.com/v1",
        env_var: "DEEPSEEK_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("deepseek-chat"),
    };

    pub const PERPLEXITY: ProviderInfo = ProviderInfo {
        name: "perplexity",
        base_url: "https://api.perplexity.ai",
        env_var: "PERPLEXITY_API_KEY",
        supports_tools: false, // Perplexity has different tool API
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("llama-3.1-sonar-large-128k-online"),
    };

    pub const ANYSCALE: ProviderInfo = ProviderInfo {
        name: "anyscale",
        base_url: "https://api.endpoints.anyscale.com/v1",
        env_var: "ANYSCALE_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("meta-llama/Meta-Llama-3-70B-Instruct"),
    };

    pub const DEEPINFRA: ProviderInfo = ProviderInfo {
        name: "deepinfra",
        base_url: "https://api.deepinfra.com/v1/openai",
        env_var: "DEEPINFRA_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("meta-llama/Meta-Llama-3.1-70B-Instruct"),
    };

    pub const LEPTON: ProviderInfo = ProviderInfo {
        name: "lepton",
        base_url: "https://llama3-1-8b.lepton.run/api/v1",
        env_var: "LEPTON_API_KEY",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const NOVITA: ProviderInfo = ProviderInfo {
        name: "novita",
        base_url: "https://api.novita.ai/v3/openai",
        env_var: "NOVITA_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("meta-llama/llama-3.1-70b-instruct"),
    };

    pub const HYPERBOLIC: ProviderInfo = ProviderInfo {
        name: "hyperbolic",
        base_url: "https://api.hyperbolic.xyz/v1",
        env_var: "HYPERBOLIC_API_KEY",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("meta-llama/Meta-Llama-3.1-70B-Instruct"),
    };

    pub const CEREBRAS: ProviderInfo = ProviderInfo {
        name: "cerebras",
        base_url: "https://api.cerebras.ai/v1",
        env_var: "CEREBRAS_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("llama3.1-70b"),
    };

    // Local providers (no API key required)

    pub const LM_STUDIO: ProviderInfo = ProviderInfo {
        name: "lm_studio",
        base_url: "http://localhost:1234/v1",
        env_var: "",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    pub const VLLM: ProviderInfo = ProviderInfo {
        name: "vllm",
        base_url: "http://localhost:8000/v1",
        env_var: "",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    pub const TGI: ProviderInfo = ProviderInfo {
        name: "tgi",
        base_url: "http://localhost:8080/v1",
        env_var: "",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const LLAMAFILE: ProviderInfo = ProviderInfo {
        name: "llamafile",
        base_url: "http://localhost:8080/v1",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    // ========== Additional Cloud Providers ==========

    pub const MODAL: ProviderInfo = ProviderInfo {
        name: "modal",
        base_url: "https://api.modal.com/v1",
        env_var: "MODAL_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const LAMBDA_LABS: ProviderInfo = ProviderInfo {
        name: "lambda",
        base_url: "https://cloud.lambdalabs.com/api/v1",
        env_var: "LAMBDA_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const FRIENDLI: ProviderInfo = ProviderInfo {
        name: "friendli",
        base_url: "https://inference.friendli.ai/v1",
        env_var: "FRIENDLI_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    pub const OCTO_AI: ProviderInfo = ProviderInfo {
        name: "octoai",
        base_url: "https://text.octoai.run/v1",
        env_var: "OCTOAI_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("meta-llama-3.1-70b-instruct"),
    };

    pub const PREDIBASE: ProviderInfo = ProviderInfo {
        name: "predibase",
        base_url: "https://serving.predibase.com/v1",
        env_var: "PREDIBASE_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const NEBIUS: ProviderInfo = ProviderInfo {
        name: "nebius",
        base_url: "https://api.studio.nebius.ai/v1",
        env_var: "NEBIUS_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("meta-llama/Meta-Llama-3.1-70B-Instruct"),
    };

    pub const SILICONFLOW: ProviderInfo = ProviderInfo {
        name: "siliconflow",
        base_url: "https://api.siliconflow.cn/v1",
        env_var: "SILICONFLOW_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("Qwen/Qwen2.5-7B-Instruct"),
    };

    pub const MOONSHOT: ProviderInfo = ProviderInfo {
        name: "moonshot",
        base_url: "https://api.moonshot.cn/v1",
        env_var: "MOONSHOT_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("moonshot-v1-8k"),
    };

    pub const ZHIPU: ProviderInfo = ProviderInfo {
        name: "zhipu",
        base_url: "https://open.bigmodel.cn/api/paas/v4",
        env_var: "ZHIPU_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("glm-4"),
    };

    pub const YI: ProviderInfo = ProviderInfo {
        name: "yi",
        base_url: "https://api.lingyiwanwu.com/v1",
        env_var: "YI_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("yi-large"),
    };

    pub const MINIMAX: ProviderInfo = ProviderInfo {
        name: "minimax",
        base_url: "https://api.minimax.chat/v1",
        env_var: "MINIMAX_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("abab6-chat"),
    };

    pub const DASHSCOPE: ProviderInfo = ProviderInfo {
        name: "dashscope",
        base_url: "https://dashscope.aliyuncs.com/compatible-mode/v1",
        env_var: "DASHSCOPE_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("qwen-turbo"),
    };

    // ========== Additional Local Inference Servers ==========

    pub const XINFERENCE: ProviderInfo = ProviderInfo {
        name: "xinference",
        base_url: "http://localhost:9997/v1",
        env_var: "",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    pub const FASTCHAT: ProviderInfo = ProviderInfo {
        name: "fastchat",
        base_url: "http://localhost:21002/v1",
        env_var: "",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const APHRODITE: ProviderInfo = ProviderInfo {
        name: "aphrodite",
        base_url: "http://localhost:2242/v1",
        env_var: "",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    pub const TABBY: ProviderInfo = ProviderInfo {
        name: "tabby",
        base_url: "http://localhost:8080/v1",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const KOBOLDCPP: ProviderInfo = ProviderInfo {
        name: "koboldcpp",
        base_url: "http://localhost:5001/v1",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const TEXT_GEN_WEBUI: ProviderInfo = ProviderInfo {
        name: "text-gen-webui",
        base_url: "http://localhost:5000/v1",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    // ========== New Tier 1 Providers ==========

    pub const XAI: ProviderInfo = ProviderInfo {
        name: "xai",
        base_url: "https://api.x.ai/v1",
        env_var: "XAI_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("grok-2-latest"),
    };

    pub const NVIDIA_NIM: ProviderInfo = ProviderInfo {
        name: "nvidia",
        base_url: "https://integrate.api.nvidia.com/v1",
        env_var: "NVIDIA_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("meta/llama-3.1-70b-instruct"),
    };

    pub const GITHUB_MODELS: ProviderInfo = ProviderInfo {
        name: "github",
        base_url: "https://models.inference.ai.azure.com",
        env_var: "GITHUB_TOKEN",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("gpt-4o"),
    };

    pub const AZURE_AI: ProviderInfo = ProviderInfo {
        name: "azure_ai",
        base_url: "https://api.ai.azure.com/v1",
        env_var: "AZURE_AI_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    // ========== New Tier 2 Providers ==========

    pub const FEATHERLESS: ProviderInfo = ProviderInfo {
        name: "featherless",
        base_url: "https://api.featherless.ai/v1",
        env_var: "FEATHERLESS_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const NSCALE: ProviderInfo = ProviderInfo {
        name: "nscale",
        base_url: "https://inference.nscale.com/v1",
        env_var: "NSCALE_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const VOLCENGINE: ProviderInfo = ProviderInfo {
        name: "volcengine",
        base_url: "https://ark.cn-beijing.volces.com/api/v3",
        env_var: "VOLCENGINE_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    pub const OVHCLOUD: ProviderInfo = ProviderInfo {
        name: "ovhcloud",
        base_url:
            "https://llama-3-1-70b-instruct.endpoints.kepler.ai.cloud.ovh.net/api/openai_compat/v1",
        env_var: "OVHCLOUD_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const GALADRIEL: ProviderInfo = ProviderInfo {
        name: "galadriel",
        base_url: "https://api.galadriel.com/v1",
        env_var: "GALADRIEL_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    // ========== New Local/Self-hosted Providers ==========

    pub const INFINITY: ProviderInfo = ProviderInfo {
        name: "infinity",
        base_url: "http://localhost:7997/v1",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const PETALS: ProviderInfo = ProviderInfo {
        name: "petals",
        base_url: "https://chat.petals.dev/api/v1",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const TRITON: ProviderInfo = ProviderInfo {
        name: "triton",
        base_url: "http://localhost:8000/v2/models",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    // ========== New Emerging Providers ==========

    pub const BYTEZ: ProviderInfo = ProviderInfo {
        name: "bytez",
        base_url: "https://api.bytez.com/v1",
        env_var: "BYTEZ_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const MORPH: ProviderInfo = ProviderInfo {
        name: "morph",
        base_url: "https://api.morphllm.com/v1",
        env_var: "MORPH_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const KLUSTER: ProviderInfo = ProviderInfo {
        name: "kluster",
        base_url: "https://api.kluster.ai/v1",
        env_var: "KLUSTER_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    // ========== Phase 2.3 Providers ==========

    pub const CHUTES: ProviderInfo = ProviderInfo {
        name: "chutes",
        base_url: "https://api.chutes.ai/v1",
        env_var: "CHUTES_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const COMET_API: ProviderInfo = ProviderInfo {
        name: "comet_api",
        base_url: "https://api.cometapi.com/v1",
        env_var: "COMET_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    pub const COMPACTIFAI: ProviderInfo = ProviderInfo {
        name: "compactifai",
        base_url: "https://api.compactifai.com/v1",
        env_var: "COMPACTIFAI_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    pub const SYNTHETIC: ProviderInfo = ProviderInfo {
        name: "synthetic",
        base_url: "https://api.synthetic.new/v1",
        env_var: "SYNTHETIC_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    pub const HEROKU_AI: ProviderInfo = ProviderInfo {
        name: "heroku_ai",
        base_url: "https://inference.heroku.com/v1",
        env_var: "HEROKU_AI_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    pub const V0: ProviderInfo = ProviderInfo {
        name: "v0",
        base_url: "https://api.v0.dev/v1",
        env_var: "V0_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    // ========== Enterprise/Commercial Providers ==========

    /// Writer AI - Enterprise AI platform
    pub const WRITER: ProviderInfo = ProviderInfo {
        name: "writer",
        base_url: "https://api.writer.com/v1",
        env_var: "WRITER_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("palmyra-x-004"),
    };

    /// Upstage - Korean AI company (Solar models)
    pub const UPSTAGE: ProviderInfo = ProviderInfo {
        name: "upstage",
        base_url: "https://api.upstage.ai/v1/solar",
        env_var: "UPSTAGE_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("solar-pro"),
    };

    /// AI/ML API - Model aggregator
    pub const AIML_API: ProviderInfo = ProviderInfo {
        name: "aimlapi",
        base_url: "https://api.aimlapi.com/v1",
        env_var: "AIML_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    /// Prem AI - Self-hosted AI platform
    pub const PREM: ProviderInfo = ProviderInfo {
        name: "prem",
        base_url: "https://api.premai.io/v1",
        env_var: "PREM_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Martian - AI router/gateway
    pub const MARTIAN: ProviderInfo = ProviderInfo {
        name: "martian",
        base_url: "https://api.withmartian.com/v1",
        env_var: "MARTIAN_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    /// Centml - GPU cloud inference
    pub const CENTML: ProviderInfo = ProviderInfo {
        name: "centml",
        base_url: "https://api.centml.com/openai/v1",
        env_var: "CENTML_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Crusoe - Cloud GPU provider
    pub const CRUSOE: ProviderInfo = ProviderInfo {
        name: "crusoe",
        base_url: "https://inference.api.crusoecloud.com/v1",
        env_var: "CRUSOE_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// CoreWeave - Cloud GPU provider
    pub const COREWEAVE: ProviderInfo = ProviderInfo {
        name: "coreweave",
        base_url: "https://inference.coreweave.com/v1",
        env_var: "COREWEAVE_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Lightning AI - ML platform
    pub const LIGHTNING: ProviderInfo = ProviderInfo {
        name: "lightning",
        base_url: "https://api.lightning.ai/v1",
        env_var: "LIGHTNING_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Cerebrium - Serverless ML
    pub const CEREBRIUM: ProviderInfo = ProviderInfo {
        name: "cerebrium",
        base_url: "https://api.cortex.cerebrium.ai/v1",
        env_var: "CEREBRIUM_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Banana - Serverless GPU
    pub const BANANA: ProviderInfo = ProviderInfo {
        name: "banana",
        base_url: "https://api.banana.dev/v1",
        env_var: "BANANA_API_KEY",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Beam - Serverless GPU
    pub const BEAM: ProviderInfo = ProviderInfo {
        name: "beam",
        base_url: "https://api.beam.cloud/v1",
        env_var: "BEAM_API_KEY",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Mystic - ML inference platform
    pub const MYSTIC: ProviderInfo = ProviderInfo {
        name: "mystic",
        base_url: "https://api.mystic.ai/v1",
        env_var: "MYSTIC_API_KEY",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    // ========== Regional/Specialized Providers ==========

    /// Baichuan - Chinese AI (Baichuan models)
    pub const BAICHUAN: ProviderInfo = ProviderInfo {
        name: "baichuan",
        base_url: "https://api.baichuan-ai.com/v1",
        env_var: "BAICHUAN_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("Baichuan2-Turbo"),
    };

    /// Qwen via Alibaba DashScope
    pub const QWEN: ProviderInfo = ProviderInfo {
        name: "qwen",
        base_url: "https://dashscope.aliyuncs.com/compatible-mode/v1",
        env_var: "DASHSCOPE_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("qwen-turbo"),
    };

    /// Stepfun (Step-1/2 models)
    pub const STEPFUN: ProviderInfo = ProviderInfo {
        name: "stepfun",
        base_url: "https://api.stepfun.com/v1",
        env_var: "STEPFUN_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("step-1-8k"),
    };

    /// 360 AI (Chinese provider)
    pub const AI360: ProviderInfo = ProviderInfo {
        name: "ai360",
        base_url: "https://api.360.cn/v1",
        env_var: "AI360_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Spark (iFlytek)
    pub const SPARK: ProviderInfo = ProviderInfo {
        name: "spark",
        base_url: "https://spark-api-open.xf-yun.com/v1",
        env_var: "SPARK_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("generalv3.5"),
    };

    /// Ernie (Baidu)
    pub const ERNIE: ProviderInfo = ProviderInfo {
        name: "ernie",
        base_url: "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop",
        env_var: "ERNIE_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("ernie-4.0-8k"),
    };

    /// Hunyuan (Tencent)
    pub const HUNYUAN: ProviderInfo = ProviderInfo {
        name: "hunyuan",
        base_url: "https://hunyuan.tencentcloudapi.com/v1",
        env_var: "HUNYUAN_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("hunyuan-pro"),
    };

    // ========== Additional Local/Self-hosted ==========

    /// LocalAI - Local OpenAI alternative
    pub const LOCAL_AI: ProviderInfo = ProviderInfo {
        name: "localai",
        base_url: "http://localhost:8080/v1",
        env_var: "",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    /// GPT4All - Local models
    pub const GPT4ALL: ProviderInfo = ProviderInfo {
        name: "gpt4all",
        base_url: "http://localhost:4891/v1",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Jan.ai - Local AI assistant
    pub const JAN: ProviderInfo = ProviderInfo {
        name: "jan",
        base_url: "http://localhost:1337/v1",
        env_var: "",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// OpenLLM - BentoML's LLM server
    pub const OPENLLM: ProviderInfo = ProviderInfo {
        name: "openllm",
        base_url: "http://localhost:3000/v1",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Nitro - Jan's inference engine
    pub const NITRO: ProviderInfo = ProviderInfo {
        name: "nitro",
        base_url: "http://localhost:3928/v1",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// MLC LLM - Machine Learning Compilation
    pub const MLC_LLM: ProviderInfo = ProviderInfo {
        name: "mlc",
        base_url: "http://localhost:8000/v1",
        env_var: "",
        supports_tools: false,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    // ========== Proxy/Gateway Providers ==========

    /// Generic OpenAI-compatible Proxy
    pub const OPENAI_PROXY: ProviderInfo = ProviderInfo {
        name: "openai_proxy",
        base_url: "http://localhost:4000/v1",
        env_var: "OPENAI_PROXY_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    /// Portkey - AI gateway
    pub const PORTKEY: ProviderInfo = ProviderInfo {
        name: "portkey",
        base_url: "https://api.portkey.ai/v1",
        env_var: "PORTKEY_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    /// Helicone - Observability proxy
    pub const HELICONE: ProviderInfo = ProviderInfo {
        name: "helicone",
        base_url: "https://oai.helicone.ai/v1",
        env_var: "HELICONE_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    /// Unify - AI gateway
    pub const UNIFY: ProviderInfo = ProviderInfo {
        name: "unify",
        base_url: "https://api.unify.ai/v0",
        env_var: "UNIFY_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    /// Keywords AI - AI gateway
    pub const KEYWORDS_AI: ProviderInfo = ProviderInfo {
        name: "keywordsai",
        base_url: "https://api.keywordsai.co/api",
        env_var: "KEYWORDS_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    // ========== European Regional Providers ==========

    /// Scaleway Generative APIs (France) - EU sovereign compute
    pub const SCALEWAY: ProviderInfo = ProviderInfo {
        name: "scaleway",
        base_url: "https://api.scaleway.ai/v1",
        env_var: "SCALEWAY_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("llama-3.3-70b-instruct"),
    };

    /// LightOn Paradigm (France) - Alfred models, sovereign deployment
    pub const LIGHTON: ProviderInfo = ProviderInfo {
        name: "lighton",
        base_url: "https://paradigm.lighton.ai/api/v2",
        env_var: "LIGHTON_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("alfred-40b-1023"),
    };

    /// IONOS AI Model Hub (Germany) - GDPR compliant
    pub const IONOS: ProviderInfo = ProviderInfo {
        name: "ionos",
        base_url: "https://openai.inference.de-txl.ionos.com/v1",
        env_var: "IONOS_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: None,
    };

    // ========== Chinese Regional Providers ==========

    /// SenseTime SenseNova (China) - SenseNova V6, 200k context
    pub const SENSENOVA: ProviderInfo = ProviderInfo {
        name: "sensenova",
        base_url: "https://api.sensenova.cn/v1",
        env_var: "SENSENOVA_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("SenseChat-5"),
    };

    /// Kunlun Tiangong (China) - Skywork O1, 400B MoE
    pub const TIANGONG: ProviderInfo = ProviderInfo {
        name: "tiangong",
        base_url: "https://sky-api.singularity-ai.com/v1",
        env_var: "TIANGONG_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("Skywork-o1-8k"),
    };

    /// Huawei PanGu (China) - PanGu 718B, enterprise focus
    pub const PANGU: ProviderInfo = ProviderInfo {
        name: "pangu",
        base_url: "https://pangu.huaweicloud.com/v1",
        env_var: "PANGU_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: None,
    };

    // ========== Southeast Asian Providers ==========

    /// AI Singapore SEA-LION - 11 Southeast Asian languages
    pub const SEA_LION: ProviderInfo = ProviderInfo {
        name: "sea-lion",
        base_url: "https://api.sea-lion.ai/v1",
        env_var: "SEA_LION_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("aisingapore/Qwen-SEA-LION-v4-32B-IT"),
    };

    // ========== Meta Providers ==========

    /// Meta Llama API - Direct access to Llama models
    pub const META_LLAMA: ProviderInfo = ProviderInfo {
        name: "meta_llama",
        base_url: "https://api.llama-api.com/v1",
        env_var: "META_LLAMA_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("llama-3.1-70b"),
    };

    // ========== Phase 2: Additional Tier 1 Providers ==========

    /// Clarifai - Multimodal AI platform with OpenAI-compatible API
    pub const CLARIFAI: ProviderInfo = ProviderInfo {
        name: "clarifai",
        base_url: "https://api.clarifai.com/v1",
        env_var: "CLARIFAI_API_KEY",
        supports_tools: false,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("claude-3-5-sonnet"),
    };

    /// Vercel AI Gateway - Unified gateway for multiple LLM providers
    pub const VERCEL_AI: ProviderInfo = ProviderInfo {
        name: "vercel_ai",
        base_url: "https://gateway.ai.cloudflare.com/v1/vercel",
        env_var: "VERCEL_AI_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("gpt-4o"),
    };

    /// Poe (Quora) - Access to multiple LLM models through Poe's platform
    pub const POE: ProviderInfo = ProviderInfo {
        name: "poe",
        base_url: "https://api.poe.com/v1",
        env_var: "POE_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("claude-3-5-sonnet-20241022"),
    };

    /// GradientAI - LLM API by DigitalOcean App Platform
    pub const GRADIENT: ProviderInfo = ProviderInfo {
        name: "gradient",
        base_url: "https://api.gradient.ai/v1",
        env_var: "GRADIENT_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("claude-3-sonnet-20240229"),
    };

    /// Reka AI - Multimodal model API
    pub const REKA: ProviderInfo = ProviderInfo {
        name: "reka",
        base_url: "https://api.reka.ai/v1",
        env_var: "REKA_API_KEY",
        supports_tools: true,
        supports_vision: true,
        supports_streaming: true,
        default_model: Some("reka-flash-research"),
    };

    /// PublicAI - Sovereign model hosting platform
    pub const PUBLIC_AI: ProviderInfo = ProviderInfo {
        name: "public_ai",
        base_url: "https://api.publicai.co/v1",
        env_var: "PUBLIC_AI_API_KEY",
        supports_tools: true,
        supports_vision: false,
        supports_streaming: true,
        default_model: Some("swiss-ai/apertus-8b-instruct"),
    };
}

/// Generic provider for any OpenAI-compatible API.
///
/// This single provider implementation works with Together AI, Fireworks AI,
/// DeepSeek, Perplexity, and many other providers that use OpenAI's API format.
pub struct OpenAICompatibleProvider {
    config: ProviderConfig,
    client: Client,
    provider_info: ProviderInfo,
}

impl OpenAICompatibleProvider {
    // ========== Factory Methods for Known Providers ==========

    /// Create a Together AI provider from environment.
    pub fn together_from_env() -> Result<Self> {
        Self::from_info(known_providers::TOGETHER)
    }

    /// Create a Together AI provider with API key.
    pub fn together(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::TOGETHER, api_key)
    }

    /// Create a Fireworks AI provider from environment.
    pub fn fireworks_from_env() -> Result<Self> {
        Self::from_info(known_providers::FIREWORKS)
    }

    /// Create a Fireworks AI provider with API key.
    pub fn fireworks(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::FIREWORKS, api_key)
    }

    /// Create a DeepSeek provider from environment.
    pub fn deepseek_from_env() -> Result<Self> {
        Self::from_info(known_providers::DEEPSEEK)
    }

    /// Create a DeepSeek provider with API key.
    pub fn deepseek(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::DEEPSEEK, api_key)
    }

    /// Create a Perplexity provider from environment.
    pub fn perplexity_from_env() -> Result<Self> {
        Self::from_info(known_providers::PERPLEXITY)
    }

    /// Create a Perplexity provider with API key.
    pub fn perplexity(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::PERPLEXITY, api_key)
    }

    /// Create an Anyscale provider from environment.
    pub fn anyscale_from_env() -> Result<Self> {
        Self::from_info(known_providers::ANYSCALE)
    }

    /// Create an Anyscale provider with API key.
    pub fn anyscale(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::ANYSCALE, api_key)
    }

    /// Create a DeepInfra provider from environment.
    pub fn deepinfra_from_env() -> Result<Self> {
        Self::from_info(known_providers::DEEPINFRA)
    }

    /// Create a DeepInfra provider with API key.
    pub fn deepinfra(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::DEEPINFRA, api_key)
    }

    /// Create a Lepton AI provider from environment.
    pub fn lepton_from_env() -> Result<Self> {
        Self::from_info(known_providers::LEPTON)
    }

    /// Create a Lepton AI provider with API key and custom base URL.
    ///
    /// Lepton requires specifying the model endpoint URL.
    pub fn lepton(api_key: impl Into<String>, base_url: impl Into<String>) -> Result<Self> {
        let mut info = known_providers::LEPTON;
        let base_url_string = base_url.into();
        // We need to own the string, so we leak it (this is fine for static provider info)
        let leaked: &'static str = Box::leak(base_url_string.into_boxed_str());
        info.base_url = leaked;
        Self::from_info_with_key(info, api_key)
    }

    /// Create a Novita AI provider from environment.
    pub fn novita_from_env() -> Result<Self> {
        Self::from_info(known_providers::NOVITA)
    }

    /// Create a Novita AI provider with API key.
    pub fn novita(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::NOVITA, api_key)
    }

    /// Create a Hyperbolic provider from environment.
    pub fn hyperbolic_from_env() -> Result<Self> {
        Self::from_info(known_providers::HYPERBOLIC)
    }

    /// Create a Hyperbolic provider with API key.
    pub fn hyperbolic(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::HYPERBOLIC, api_key)
    }

    /// Create a Cerebras provider from environment.
    pub fn cerebras_from_env() -> Result<Self> {
        Self::from_info(known_providers::CEREBRAS)
    }

    /// Create a Cerebras provider with API key.
    pub fn cerebras(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::CEREBRAS, api_key)
    }

    // ========== Additional Cloud Providers (includes local providers) ==========

    /// Create a Modal provider from environment.
    pub fn modal_from_env() -> Result<Self> {
        Self::from_info(known_providers::MODAL)
    }

    /// Create a Modal provider with API key.
    pub fn modal(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::MODAL, api_key)
    }

    /// Create a FriendliAI provider from environment.
    pub fn friendli_from_env() -> Result<Self> {
        Self::from_info(known_providers::FRIENDLI)
    }

    /// Create a FriendliAI provider with API key.
    pub fn friendli(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::FRIENDLI, api_key)
    }

    /// Create an OctoAI provider from environment.
    pub fn octoai_from_env() -> Result<Self> {
        Self::from_info(known_providers::OCTO_AI)
    }

    /// Create an OctoAI provider with API key.
    pub fn octoai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::OCTO_AI, api_key)
    }

    /// Create a Predibase provider from environment.
    pub fn predibase_from_env() -> Result<Self> {
        Self::from_info(known_providers::PREDIBASE)
    }

    /// Create a Predibase provider with API key.
    pub fn predibase(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::PREDIBASE, api_key)
    }

    /// Create a Nebius AI provider from environment.
    pub fn nebius_from_env() -> Result<Self> {
        Self::from_info(known_providers::NEBIUS)
    }

    /// Create a Nebius AI provider with API key.
    pub fn nebius(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::NEBIUS, api_key)
    }

    /// Create a SiliconFlow provider from environment.
    pub fn siliconflow_from_env() -> Result<Self> {
        Self::from_info(known_providers::SILICONFLOW)
    }

    /// Create a SiliconFlow provider with API key.
    pub fn siliconflow(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::SILICONFLOW, api_key)
    }

    /// Create a Moonshot AI provider from environment.
    pub fn moonshot_from_env() -> Result<Self> {
        Self::from_info(known_providers::MOONSHOT)
    }

    /// Create a Moonshot AI provider with API key.
    pub fn moonshot(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::MOONSHOT, api_key)
    }

    /// Create a Zhipu AI (GLM) provider from environment.
    pub fn zhipu_from_env() -> Result<Self> {
        Self::from_info(known_providers::ZHIPU)
    }

    /// Create a Zhipu AI (GLM) provider with API key.
    pub fn zhipu(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::ZHIPU, api_key)
    }

    /// Create a 01.AI (Yi) provider from environment.
    pub fn yi_from_env() -> Result<Self> {
        Self::from_info(known_providers::YI)
    }

    /// Create a 01.AI (Yi) provider with API key.
    pub fn yi(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::YI, api_key)
    }

    /// Create a Minimax provider from environment.
    pub fn minimax_from_env() -> Result<Self> {
        Self::from_info(known_providers::MINIMAX)
    }

    /// Create a Minimax provider with API key.
    pub fn minimax(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::MINIMAX, api_key)
    }

    /// Create an Alibaba DashScope (Qwen) provider from environment.
    pub fn dashscope_from_env() -> Result<Self> {
        Self::from_info(known_providers::DASHSCOPE)
    }

    /// Create an Alibaba DashScope (Qwen) provider with API key.
    pub fn dashscope(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::DASHSCOPE, api_key)
    }

    // ========== New Tier 1 Cloud Providers ==========

    /// Create an xAI (Grok) provider from environment.
    pub fn xai_from_env() -> Result<Self> {
        Self::from_info(known_providers::XAI)
    }

    /// Create an xAI (Grok) provider with API key.
    pub fn xai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::XAI, api_key)
    }

    /// Create a GitHub Models provider from environment.
    pub fn github_models_from_env() -> Result<Self> {
        Self::from_info(known_providers::GITHUB_MODELS)
    }

    /// Create a GitHub Models provider with API key (GitHub token).
    pub fn github_models(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::GITHUB_MODELS, api_key)
    }

    /// Create an Azure AI provider from environment.
    pub fn azure_ai_from_env() -> Result<Self> {
        Self::from_info(known_providers::AZURE_AI)
    }

    /// Create an Azure AI provider with API key.
    pub fn azure_ai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::AZURE_AI, api_key)
    }

    // ========== New Tier 2 Cloud Providers ==========

    /// Create a Featherless AI provider from environment.
    pub fn featherless_from_env() -> Result<Self> {
        Self::from_info(known_providers::FEATHERLESS)
    }

    /// Create a Featherless AI provider with API key.
    pub fn featherless(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::FEATHERLESS, api_key)
    }

    /// Create an Nscale provider from environment.
    pub fn nscale_from_env() -> Result<Self> {
        Self::from_info(known_providers::NSCALE)
    }

    /// Create an Nscale provider with API key.
    pub fn nscale(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::NSCALE, api_key)
    }

    /// Create a Volcengine (ByteDance) provider from environment.
    pub fn volcengine_from_env() -> Result<Self> {
        Self::from_info(known_providers::VOLCENGINE)
    }

    /// Create a Volcengine (ByteDance) provider with API key.
    pub fn volcengine(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::VOLCENGINE, api_key)
    }

    /// Create an OVHcloud AI provider from environment.
    pub fn ovhcloud_from_env() -> Result<Self> {
        Self::from_info(known_providers::OVHCLOUD)
    }

    /// Create an OVHcloud AI provider with API key.
    pub fn ovhcloud(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::OVHCLOUD, api_key)
    }

    /// Create a Galadriel provider from environment.
    pub fn galadriel_from_env() -> Result<Self> {
        Self::from_info(known_providers::GALADRIEL)
    }

    /// Create a Galadriel provider with API key.
    pub fn galadriel(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::GALADRIEL, api_key)
    }

    // ========== New Local/Self-hosted Providers ==========

    // ========== New Emerging Providers ==========

    /// Create a Bytez provider from environment.
    pub fn bytez_from_env() -> Result<Self> {
        Self::from_info(known_providers::BYTEZ)
    }

    /// Create a Bytez provider with API key.
    pub fn bytez(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::BYTEZ, api_key)
    }

    /// Create a Bytez provider with config.
    pub fn bytez_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::BYTEZ, config)
    }

    /// Create a Morph provider from environment.
    pub fn morph_from_env() -> Result<Self> {
        Self::from_info(known_providers::MORPH)
    }

    /// Create a Morph provider with API key.
    pub fn morph(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::MORPH, api_key)
    }

    /// Create a Morph provider with config.
    pub fn morph_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::MORPH, config)
    }

    /// Create a Kluster provider from environment.
    pub fn kluster_from_env() -> Result<Self> {
        Self::from_info(known_providers::KLUSTER)
    }

    /// Create a Kluster provider with API key.
    pub fn kluster(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::KLUSTER, api_key)
    }

    // ========== Enterprise/Commercial Providers ==========

    /// Create a Writer AI provider from environment.
    pub fn writer_from_env() -> Result<Self> {
        Self::from_info(known_providers::WRITER)
    }

    /// Create a Writer AI provider with API key.
    pub fn writer(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::WRITER, api_key)
    }

    /// Create an Upstage (Solar) provider from environment.
    pub fn upstage_from_env() -> Result<Self> {
        Self::from_info(known_providers::UPSTAGE)
    }

    /// Create an Upstage (Solar) provider with API key.
    pub fn upstage(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::UPSTAGE, api_key)
    }

    /// Create an AI/ML API provider from environment.
    pub fn aimlapi_from_env() -> Result<Self> {
        Self::from_info(known_providers::AIML_API)
    }

    /// Create an AI/ML API provider with API key.
    pub fn aimlapi(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::AIML_API, api_key)
    }

    /// Create a Prem AI provider from environment.
    pub fn prem_from_env() -> Result<Self> {
        Self::from_info(known_providers::PREM)
    }

    /// Create a Prem AI provider with API key.
    pub fn prem(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::PREM, api_key)
    }

    /// Create a Martian provider from environment.
    pub fn martian_from_env() -> Result<Self> {
        Self::from_info(known_providers::MARTIAN)
    }

    /// Create a Martian provider with API key.
    pub fn martian(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::MARTIAN, api_key)
    }

    /// Create a Centml provider from environment.
    pub fn centml_from_env() -> Result<Self> {
        Self::from_info(known_providers::CENTML)
    }

    /// Create a Centml provider with API key.
    pub fn centml(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::CENTML, api_key)
    }

    /// Create a Crusoe Cloud provider from environment.
    pub fn crusoe_from_env() -> Result<Self> {
        Self::from_info(known_providers::CRUSOE)
    }

    /// Create a Crusoe Cloud provider with API key.
    pub fn crusoe(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::CRUSOE, api_key)
    }

    /// Create a CoreWeave provider from environment.
    pub fn coreweave_from_env() -> Result<Self> {
        Self::from_info(known_providers::COREWEAVE)
    }

    /// Create a CoreWeave provider with API key.
    pub fn coreweave(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::COREWEAVE, api_key)
    }

    /// Create a Lightning AI provider from environment.
    pub fn lightning_from_env() -> Result<Self> {
        Self::from_info(known_providers::LIGHTNING)
    }

    /// Create a Lightning AI provider with API key.
    pub fn lightning(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::LIGHTNING, api_key)
    }

    /// Create a Cerebrium provider from environment.
    pub fn cerebrium_from_env() -> Result<Self> {
        Self::from_info(known_providers::CEREBRIUM)
    }

    /// Create a Cerebrium provider with API key.
    pub fn cerebrium(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::CEREBRIUM, api_key)
    }

    /// Create a Banana provider from environment.
    pub fn banana_from_env() -> Result<Self> {
        Self::from_info(known_providers::BANANA)
    }

    /// Create a Banana provider with API key.
    pub fn banana(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::BANANA, api_key)
    }

    /// Create a Beam provider from environment.
    pub fn beam_from_env() -> Result<Self> {
        Self::from_info(known_providers::BEAM)
    }

    /// Create a Beam provider with API key.
    pub fn beam(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::BEAM, api_key)
    }

    /// Create a Mystic provider from environment.
    pub fn mystic_from_env() -> Result<Self> {
        Self::from_info(known_providers::MYSTIC)
    }

    /// Create a Mystic provider with API key.
    pub fn mystic(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::MYSTIC, api_key)
    }

    // ========== Regional/Specialized Providers ==========

    /// Create a Baichuan provider from environment.
    pub fn baichuan_from_env() -> Result<Self> {
        Self::from_info(known_providers::BAICHUAN)
    }

    /// Create a Baichuan provider with API key.
    pub fn baichuan(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::BAICHUAN, api_key)
    }

    /// Create a Qwen (DashScope) provider from environment.
    pub fn qwen_from_env() -> Result<Self> {
        Self::from_info(known_providers::QWEN)
    }

    /// Create a Qwen (DashScope) provider with API key.
    pub fn qwen(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::QWEN, api_key)
    }

    /// Create a Stepfun provider from environment.
    pub fn stepfun_from_env() -> Result<Self> {
        Self::from_info(known_providers::STEPFUN)
    }

    /// Create a Stepfun provider with API key.
    pub fn stepfun(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::STEPFUN, api_key)
    }

    /// Create a 360 AI provider from environment.
    pub fn ai360_from_env() -> Result<Self> {
        Self::from_info(known_providers::AI360)
    }

    /// Create a 360 AI provider with API key.
    pub fn ai360(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::AI360, api_key)
    }

    /// Create a Spark (iFlytek) provider from environment.
    pub fn spark_from_env() -> Result<Self> {
        Self::from_info(known_providers::SPARK)
    }

    /// Create a Spark (iFlytek) provider with API key.
    pub fn spark(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::SPARK, api_key)
    }

    /// Create an Ernie (Baidu) provider from environment.
    pub fn ernie_from_env() -> Result<Self> {
        Self::from_info(known_providers::ERNIE)
    }

    /// Create an Ernie (Baidu) provider with API key.
    pub fn ernie(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::ERNIE, api_key)
    }

    /// Create a Hunyuan (Tencent) provider from environment.
    pub fn hunyuan_from_env() -> Result<Self> {
        Self::from_info(known_providers::HUNYUAN)
    }

    /// Create a Hunyuan (Tencent) provider with API key.
    pub fn hunyuan(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::HUNYUAN, api_key)
    }

    /// Create a Portkey gateway provider from environment.
    pub fn portkey_from_env() -> Result<Self> {
        Self::from_info(known_providers::PORTKEY)
    }

    /// Create a Portkey gateway provider with API key.
    pub fn portkey(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::PORTKEY, api_key)
    }

    /// Create a Helicone proxy provider from environment.
    pub fn helicone_from_env() -> Result<Self> {
        Self::from_info(known_providers::HELICONE)
    }

    /// Create a Helicone proxy provider with API key.
    pub fn helicone(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::HELICONE, api_key)
    }

    /// Create a Unify gateway provider from environment.
    pub fn unify_from_env() -> Result<Self> {
        Self::from_info(known_providers::UNIFY)
    }

    /// Create a Unify gateway provider with API key.
    pub fn unify(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::UNIFY, api_key)
    }

    /// Create a Keywords AI gateway provider from environment.
    pub fn keywordsai_from_env() -> Result<Self> {
        Self::from_info(known_providers::KEYWORDS_AI)
    }

    /// Create a Keywords AI gateway provider with API key.
    pub fn keywordsai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::KEYWORDS_AI, api_key)
    }

    // ========== European Regional Providers ==========

    /// Create a Scaleway provider from environment.
    pub fn scaleway_from_env() -> Result<Self> {
        Self::from_info(known_providers::SCALEWAY)
    }

    /// Create a Scaleway provider with API key.
    pub fn scaleway(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::SCALEWAY, api_key)
    }

    /// Create a LightOn Paradigm provider from environment.
    pub fn lighton_from_env() -> Result<Self> {
        Self::from_info(known_providers::LIGHTON)
    }

    /// Create a LightOn Paradigm provider with API key.
    pub fn lighton(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::LIGHTON, api_key)
    }

    /// Create an IONOS AI provider from environment.
    pub fn ionos_from_env() -> Result<Self> {
        Self::from_info(known_providers::IONOS)
    }

    /// Create an IONOS AI provider with API key.
    pub fn ionos(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::IONOS, api_key)
    }

    // ========== Chinese Regional Providers ==========

    /// Create a SenseTime SenseNova provider from environment.
    pub fn sensenova_from_env() -> Result<Self> {
        Self::from_info(known_providers::SENSENOVA)
    }

    /// Create a SenseTime SenseNova provider with API key.
    pub fn sensenova(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::SENSENOVA, api_key)
    }

    /// Create a Kunlun Tiangong provider from environment.
    pub fn tiangong_from_env() -> Result<Self> {
        Self::from_info(known_providers::TIANGONG)
    }

    /// Create a Kunlun Tiangong provider with API key.
    pub fn tiangong(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::TIANGONG, api_key)
    }

    /// Create a Huawei PanGu provider from environment.
    pub fn pangu_from_env() -> Result<Self> {
        Self::from_info(known_providers::PANGU)
    }

    /// Create a Huawei PanGu provider with API key.
    pub fn pangu(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::PANGU, api_key)
    }

    // ========== Southeast Asian Providers ==========

    /// Create an AI Singapore SEA-LION provider from environment.
    pub fn sea_lion_from_env() -> Result<Self> {
        Self::from_info(known_providers::SEA_LION)
    }

    /// Create an AI Singapore SEA-LION provider with API key.
    pub fn sea_lion(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::SEA_LION, api_key)
    }

    /// Create a Meta Llama API provider from environment.
    pub fn meta_llama_from_env() -> Result<Self> {
        Self::from_info(known_providers::META_LLAMA)
    }

    /// Create a Meta Llama API provider with API key.
    pub fn meta_llama(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::META_LLAMA, api_key)
    }

    /// Create an AIML API provider from environment.
    pub fn aiml_api_from_env() -> Result<Self> {
        Self::from_info(known_providers::AIML_API)
    }

    /// Create an AIML API provider with API key.
    pub fn aiml_api(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::AIML_API, api_key)
    }

    /// Create an Aphrodite provider from environment.
    pub fn aphrodite_from_env() -> Result<Self> {
        Self::from_info(known_providers::APHRODITE)
    }

    /// Create an Aphrodite provider with API key.
    pub fn aphrodite(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::APHRODITE, api_key)
    }

    /// Create a FastChat provider from environment.
    pub fn fastchat_from_env() -> Result<Self> {
        Self::from_info(known_providers::FASTCHAT)
    }

    /// Create a FastChat provider with API key.
    pub fn fastchat(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::FASTCHAT, api_key)
    }

    /// Create an Infinity provider from environment.
    pub fn infinity_from_env() -> Result<Self> {
        Self::from_info(known_providers::INFINITY)
    }

    /// Create an Infinity provider with API key.
    pub fn infinity(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::INFINITY, api_key)
    }

    /// Create a Jan provider from environment.
    pub fn jan_from_env() -> Result<Self> {
        Self::from_info(known_providers::JAN)
    }

    /// Create a Jan provider with API key.
    pub fn jan(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::JAN, api_key)
    }

    /// Create a Keywords AI provider from environment.
    pub fn keywords_ai_from_env() -> Result<Self> {
        Self::from_info(known_providers::KEYWORDS_AI)
    }

    /// Create a Keywords AI provider with API key.
    pub fn keywords_ai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::KEYWORDS_AI, api_key)
    }

    /// Create a KoboldCpp provider from environment.
    pub fn koboldcpp_from_env() -> Result<Self> {
        Self::from_info(known_providers::KOBOLDCPP)
    }

    /// Create a KoboldCpp provider with API key.
    pub fn koboldcpp(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::KOBOLDCPP, api_key)
    }

    /// Create an OpenAI-compatible proxy provider from environment.
    pub fn openai_proxy_from_env() -> Result<Self> {
        Self::from_info(known_providers::OPENAI_PROXY)
    }

    /// Create an OpenAI-compatible proxy provider with API key.
    pub fn openai_proxy(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::OPENAI_PROXY, api_key)
    }

    /// Create a Llamafile provider from environment.
    pub fn llamafile_from_env() -> Result<Self> {
        Self::from_info(known_providers::LLAMAFILE)
    }

    /// Create a Llamafile provider with API key.
    pub fn llamafile(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::LLAMAFILE, api_key)
    }

    /// Create an LM Studio provider from environment.
    pub fn lm_studio_from_env() -> Result<Self> {
        Self::from_info(known_providers::LM_STUDIO)
    }

    /// Create an LM Studio provider with API key.
    pub fn lm_studio(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::LM_STUDIO, api_key)
    }

    /// Create a LocalAI provider from environment.
    pub fn local_ai_from_env() -> Result<Self> {
        Self::from_info(known_providers::LOCAL_AI)
    }

    /// Create a LocalAI provider with API key.
    pub fn local_ai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::LOCAL_AI, api_key)
    }

    /// Create an MLC LLM provider from environment.
    pub fn mlc_llm_from_env() -> Result<Self> {
        Self::from_info(known_providers::MLC_LLM)
    }

    /// Create an MLC LLM provider with API key.
    pub fn mlc_llm(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::MLC_LLM, api_key)
    }

    /// Create a Nitro provider from environment.
    pub fn nitro_from_env() -> Result<Self> {
        Self::from_info(known_providers::NITRO)
    }

    /// Create a Nitro provider with API key.
    pub fn nitro(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::NITRO, api_key)
    }

    /// Create an OctoAI provider from environment.
    pub fn octo_ai_from_env() -> Result<Self> {
        Self::from_info(known_providers::OCTO_AI)
    }

    /// Create an OctoAI provider with API key.
    pub fn octo_ai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::OCTO_AI, api_key)
    }

    /// Create an OpenLLM provider from environment.
    pub fn openllm_from_env() -> Result<Self> {
        Self::from_info(known_providers::OPENLLM)
    }

    /// Create an OpenLLM provider with API key.
    pub fn openllm(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::OPENLLM, api_key)
    }

    /// Create a Petals provider from environment.
    pub fn petals_from_env() -> Result<Self> {
        Self::from_info(known_providers::PETALS)
    }

    /// Create a Petals provider with API key.
    pub fn petals(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::PETALS, api_key)
    }

    /// Create a Tabby provider from environment.
    pub fn tabby_from_env() -> Result<Self> {
        Self::from_info(known_providers::TABBY)
    }

    /// Create a Tabby provider with API key.
    pub fn tabby(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::TABBY, api_key)
    }

    /// Create a Text Generation WebUI provider from environment.
    pub fn text_gen_webui_from_env() -> Result<Self> {
        Self::from_info(known_providers::TEXT_GEN_WEBUI)
    }

    /// Create a Text Generation WebUI provider with API key.
    pub fn text_gen_webui(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::TEXT_GEN_WEBUI, api_key)
    }

    /// Create a TGI provider from environment.
    pub fn tgi_from_env() -> Result<Self> {
        Self::from_info(known_providers::TGI)
    }

    /// Create a TGI provider with API key.
    pub fn tgi(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::TGI, api_key)
    }

    /// Create a Triton provider from environment.
    pub fn triton_from_env() -> Result<Self> {
        Self::from_info(known_providers::TRITON)
    }

    /// Create a Triton provider with API key.
    pub fn triton(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::TRITON, api_key)
    }

    /// Create a vLLM provider from environment.
    pub fn vllm_from_env() -> Result<Self> {
        Self::from_info(known_providers::VLLM)
    }

    /// Create a vLLM provider with API key.
    pub fn vllm(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::VLLM, api_key)
    }

    /// Create a Clarifai provider from environment.
    pub fn clarifai_from_env() -> Result<Self> {
        Self::from_info(known_providers::CLARIFAI)
    }

    /// Create a Clarifai provider with API key.
    pub fn clarifai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::CLARIFAI, api_key)
    }

    /// Create a Clarifai provider with config.
    pub fn clarifai_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::CLARIFAI, config)
    }

    /// Create a Vercel AI Gateway provider from environment.
    pub fn vercel_ai_from_env() -> Result<Self> {
        Self::from_info(known_providers::VERCEL_AI)
    }

    /// Create a Vercel AI Gateway provider with API key.
    pub fn vercel_ai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::VERCEL_AI, api_key)
    }

    /// Create a Vercel AI Gateway provider with config.
    pub fn vercel_ai_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::VERCEL_AI, config)
    }

    /// Create a Poe provider from environment.
    pub fn poe_from_env() -> Result<Self> {
        Self::from_info(known_providers::POE)
    }

    /// Create a Poe provider with API key.
    pub fn poe(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::POE, api_key)
    }

    /// Create a Poe provider with config.
    pub fn poe_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::POE, config)
    }

    /// Create a GradientAI provider from environment.
    pub fn gradient_from_env() -> Result<Self> {
        Self::from_info(known_providers::GRADIENT)
    }

    /// Create a GradientAI provider with API key.
    pub fn gradient(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::GRADIENT, api_key)
    }

    /// Create a GradientAI provider with config.
    pub fn gradient_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::GRADIENT, config)
    }

    /// Create a Reka AI provider from environment.
    pub fn reka_from_env() -> Result<Self> {
        Self::from_info(known_providers::REKA)
    }

    /// Create a Reka AI provider with API key.
    pub fn reka(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::REKA, api_key)
    }

    /// Create a Reka AI provider with config.
    pub fn reka_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::REKA, config)
    }

    /// Create a Lambda Labs provider from environment.
    pub fn lambda_from_env() -> Result<Self> {
        Self::from_info(known_providers::LAMBDA_LABS)
    }

    /// Create a Lambda Labs provider with API key.
    pub fn lambda(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::LAMBDA_LABS, api_key)
    }

    /// Create a Lambda Labs provider with config.
    pub fn lambda_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::LAMBDA_LABS, config)
    }

    /// Create a Nvidia NIM provider from environment.
    pub fn nvidia_nim_from_env() -> Result<Self> {
        Self::from_info(known_providers::NVIDIA_NIM)
    }

    /// Create a Nvidia NIM provider with API key.
    pub fn nvidia_nim(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::NVIDIA_NIM, api_key)
    }

    /// Create a Nvidia NIM provider with config.
    pub fn nvidia_nim_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::NVIDIA_NIM, config)
    }

    /// Create a Xinference provider from environment.
    pub fn xinference_from_env() -> Result<Self> {
        Self::from_info(known_providers::XINFERENCE)
    }

    /// Create a Xinference provider with API key.
    pub fn xinference(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::XINFERENCE, api_key)
    }

    /// Create a Xinference provider with config.
    pub fn xinference_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::XINFERENCE, config)
    }

    /// Create a PublicAI provider from environment.
    pub fn public_ai_from_env() -> Result<Self> {
        Self::from_info(known_providers::PUBLIC_AI)
    }

    /// Create a PublicAI provider with API key.
    pub fn public_ai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::PUBLIC_AI, api_key)
    }

    /// Create a PublicAI provider with config.
    pub fn public_ai_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::PUBLIC_AI, config)
    }

    /// Create a Chutes provider from environment.
    pub fn chutes_from_env() -> Result<Self> {
        Self::from_info(known_providers::CHUTES)
    }

    /// Create a Chutes provider with API key.
    pub fn chutes(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::CHUTES, api_key)
    }

    /// Create a Chutes provider with config.
    pub fn chutes_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::CHUTES, config)
    }

    /// Create a CometAPI provider from environment.
    pub fn comet_api_from_env() -> Result<Self> {
        Self::from_info(known_providers::COMET_API)
    }

    /// Create a CometAPI provider with API key.
    pub fn comet_api(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::COMET_API, api_key)
    }

    /// Create a CometAPI provider with config.
    pub fn comet_api_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::COMET_API, config)
    }

    /// Create a CompactifAI provider from environment.
    pub fn compactifai_from_env() -> Result<Self> {
        Self::from_info(known_providers::COMPACTIFAI)
    }

    /// Create a CompactifAI provider with API key.
    pub fn compactifai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::COMPACTIFAI, api_key)
    }

    /// Create a CompactifAI provider with config.
    pub fn compactifai_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::COMPACTIFAI, config)
    }

    /// Create a Synthetic provider from environment.
    pub fn synthetic_from_env() -> Result<Self> {
        Self::from_info(known_providers::SYNTHETIC)
    }

    /// Create a Synthetic provider with API key.
    pub fn synthetic(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::SYNTHETIC, api_key)
    }

    /// Create a Synthetic provider with config.
    pub fn synthetic_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::SYNTHETIC, config)
    }

    /// Create a Heroku AI provider from environment.
    pub fn heroku_ai_from_env() -> Result<Self> {
        Self::from_info(known_providers::HEROKU_AI)
    }

    /// Create a Heroku AI provider with API key.
    pub fn heroku_ai(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::HEROKU_AI, api_key)
    }

    /// Create a Heroku AI provider with config.
    pub fn heroku_ai_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::HEROKU_AI, config)
    }

    /// Create a v0 provider from environment.
    pub fn v0_from_env() -> Result<Self> {
        Self::from_info(known_providers::V0)
    }

    /// Create a v0 provider with API key.
    pub fn v0(api_key: impl Into<String>) -> Result<Self> {
        Self::from_info_with_key(known_providers::V0, api_key)
    }

    /// Create a v0 provider with config.
    pub fn v0_config(config: ProviderConfig) -> Result<Self> {
        Self::from_config(known_providers::V0, config)
    }

    // ========== Custom Provider ==========

    /// Create a custom OpenAI-compatible provider.
    ///
    /// Use this for any provider that uses OpenAI's API format but isn't
    /// in the pre-defined list.
    ///
    /// # Arguments
    ///
    /// * `name` - Provider name for logging
    /// * `base_url` - Base URL (e.g., "<https://api.example.com/v1>")
    /// * `api_key` - Optional API key
    ///
    /// # Example
    ///
    /// ```ignore
    /// let provider = OpenAICompatibleProvider::custom(
    ///     "my-provider",
    ///     "https://my-api.example.com/v1",
    ///     Some("my-api-key".to_string()),
    /// )?;
    /// ```
    pub fn custom(
        name: impl Into<String>,
        base_url: impl Into<String>,
        api_key: Option<String>,
    ) -> Result<Self> {
        let name_string = name.into();
        let base_url_string = base_url.into();

        // Leak strings to get static references
        let name_static: &'static str = Box::leak(name_string.into_boxed_str());
        let base_url_static: &'static str = Box::leak(base_url_string.into_boxed_str());

        let info = ProviderInfo {
            name: name_static,
            base_url: base_url_static,
            env_var: "",
            supports_tools: true,
            supports_vision: true,
            supports_streaming: true,
            default_model: None,
        };

        let config = ProviderConfig {
            api_key,
            base_url: Some(base_url_static.to_string()),
            ..Default::default()
        };

        Self::new(config, info)
    }

    // ========== Internal Construction ==========

    fn from_info(info: ProviderInfo) -> Result<Self> {
        let config = ProviderConfig::from_env(info.env_var);
        let config = config.with_base_url(info.base_url);
        Self::new(config, info)
    }

    fn from_info_with_key(info: ProviderInfo, api_key: impl Into<String>) -> Result<Self> {
        let config = ProviderConfig::new(api_key).with_base_url(info.base_url);
        Self::new(config, info)
    }

    fn from_config(info: ProviderInfo, config: ProviderConfig) -> Result<Self> {
        // If no base URL in config, use the provider's default
        let config = if config.base_url.is_none() {
            config.with_base_url(info.base_url)
        } else {
            config
        };
        Self::new(config, info)
    }

    #[allow(dead_code)]
    fn local(info: ProviderInfo) -> Result<Self> {
        let config = ProviderConfig {
            api_key: None,
            base_url: Some(info.base_url.to_string()),
            ..Default::default()
        };
        Self::new(config, info)
    }

    /// Create a new provider with custom configuration.
    pub fn new(config: ProviderConfig, provider_info: ProviderInfo) -> Result<Self> {
        let mut headers = reqwest::header::HeaderMap::new();

        if let Some(ref key) = config.api_key {
            headers.insert(
                reqwest::header::AUTHORIZATION,
                format!("Bearer {}", key)
                    .parse()
                    .map_err(|_| Error::config("Invalid API key format"))?,
            );
        }

        headers.insert(
            reqwest::header::CONTENT_TYPE,
            "application/json".parse().unwrap(),
        );

        // Add custom headers
        for (key, value) in &config.custom_headers {
            headers.insert(
                reqwest::header::HeaderName::try_from(key.as_str())
                    .map_err(|_| Error::config(format!("Invalid header name: {}", key)))?,
                value
                    .parse()
                    .map_err(|_| Error::config(format!("Invalid header value for {}", key)))?,
            );
        }

        let client = Client::builder()
            .timeout(config.timeout)
            .default_headers(headers)
            .build()?;

        Ok(Self {
            config,
            client,
            provider_info,
        })
    }

    fn api_url(&self) -> String {
        let base = self
            .config
            .base_url
            .as_deref()
            .unwrap_or(self.provider_info.base_url);

        // Ensure we have /chat/completions endpoint
        if base.ends_with("/chat/completions") {
            base.to_string()
        } else if base.ends_with('/') {
            format!("{}chat/completions", base)
        } else {
            format!("{}/chat/completions", base)
        }
    }

    /// Convert our unified request to OpenAI's format.
    fn convert_request(&self, request: &CompletionRequest) -> OpenAIRequest {
        let mut messages: Vec<OpenAIMessage> = Vec::new();

        // Add system message if present
        if let Some(ref system) = request.system {
            messages.push(OpenAIMessage {
                role: "system".to_string(),
                content: Some(OpenAIContent::Text(system.clone())),
                tool_calls: None,
                tool_call_id: None,
            });
        }

        // Convert messages
        for msg in &request.messages {
            messages.extend(self.convert_message(msg));
        }

        // Convert tools (only if provider supports them)
        let tools = if self.provider_info.supports_tools {
            request.tools.as_ref().map(|tools| {
                tools
                    .iter()
                    .map(|t| OpenAITool {
                        tool_type: "function".to_string(),
                        function: OpenAIFunction {
                            name: t.name.clone(),
                            description: Some(t.description.clone()),
                            parameters: t.input_schema.clone(),
                        },
                    })
                    .collect()
            })
        } else {
            None
        };

        OpenAIRequest {
            model: request.model.clone(),
            messages,
            max_tokens: request.max_tokens,
            temperature: request.temperature,
            top_p: request.top_p,
            stop: request.stop_sequences.clone(),
            stream: request.stream,
            tools,
            stream_options: if request.stream {
                Some(StreamOptions {
                    include_usage: true,
                })
            } else {
                None
            },
        }
    }

    fn convert_message(&self, message: &Message) -> Vec<OpenAIMessage> {
        let mut result = Vec::new();

        match message.role {
            Role::System => {
                let text = message.text_content();
                if !text.is_empty() {
                    result.push(OpenAIMessage {
                        role: "system".to_string(),
                        content: Some(OpenAIContent::Text(text)),
                        tool_calls: None,
                        tool_call_id: None,
                    });
                }
            }
            Role::User => {
                // Check if we have tool results
                let tool_results: Vec<_> = message
                    .content
                    .iter()
                    .filter_map(|b| match b {
                        ContentBlock::ToolResult {
                            tool_use_id,
                            content,
                            ..
                        } => Some((tool_use_id.clone(), content.clone())),
                        _ => None,
                    })
                    .collect();

                if !tool_results.is_empty() {
                    // Tool results become separate "tool" role messages
                    for (tool_call_id, content) in tool_results {
                        result.push(OpenAIMessage {
                            role: "tool".to_string(),
                            content: Some(OpenAIContent::Text(content)),
                            tool_calls: None,
                            tool_call_id: Some(tool_call_id),
                        });
                    }
                } else {
                    // Regular user message
                    let content_parts: Vec<OpenAIContentPart> = message
                        .content
                        .iter()
                        .filter_map(|block| match block {
                            ContentBlock::Text { text } => {
                                Some(OpenAIContentPart::Text { text: text.clone() })
                            }
                            ContentBlock::Image { media_type, data }
                                if self.provider_info.supports_vision =>
                            {
                                Some(OpenAIContentPart::ImageUrl {
                                    image_url: ImageUrl {
                                        url: format!("data:{};base64,{}", media_type, data),
                                        detail: None,
                                    },
                                })
                            }
                            ContentBlock::ImageUrl { url }
                                if self.provider_info.supports_vision =>
                            {
                                Some(OpenAIContentPart::ImageUrl {
                                    image_url: ImageUrl {
                                        url: url.clone(),
                                        detail: None,
                                    },
                                })
                            }
                            _ => None,
                        })
                        .collect();

                    if content_parts.len() == 1 {
                        if let OpenAIContentPart::Text { text } = &content_parts[0] {
                            result.push(OpenAIMessage {
                                role: "user".to_string(),
                                content: Some(OpenAIContent::Text(text.clone())),
                                tool_calls: None,
                                tool_call_id: None,
                            });
                        } else {
                            result.push(OpenAIMessage {
                                role: "user".to_string(),
                                content: Some(OpenAIContent::Parts(content_parts)),
                                tool_calls: None,
                                tool_call_id: None,
                            });
                        }
                    } else if !content_parts.is_empty() {
                        result.push(OpenAIMessage {
                            role: "user".to_string(),
                            content: Some(OpenAIContent::Parts(content_parts)),
                            tool_calls: None,
                            tool_call_id: None,
                        });
                    }
                }
            }
            Role::Assistant => {
                // Check for tool calls
                let tool_calls: Vec<OpenAIToolCall> = message
                    .content
                    .iter()
                    .filter_map(|block| match block {
                        ContentBlock::ToolUse { id, name, input } => Some(OpenAIToolCall {
                            id: id.clone(),
                            call_type: "function".to_string(),
                            function: OpenAIFunctionCall {
                                name: name.clone(),
                                arguments: input.to_string(),
                            },
                        }),
                        _ => None,
                    })
                    .collect();

                let text_content = message.text_content();

                result.push(OpenAIMessage {
                    role: "assistant".to_string(),
                    content: if text_content.is_empty() {
                        None
                    } else {
                        Some(OpenAIContent::Text(text_content))
                    },
                    tool_calls: if tool_calls.is_empty() {
                        None
                    } else {
                        Some(tool_calls)
                    },
                    tool_call_id: None,
                });
            }
        }

        result
    }

    fn convert_response(&self, response: OpenAIResponse) -> CompletionResponse {
        let choice = response.choices.into_iter().next().unwrap_or_default();
        let mut content = Vec::new();

        // Add text content
        if let Some(text) = choice.message.content {
            content.push(ContentBlock::Text { text });
        }

        // Add tool calls
        if let Some(tool_calls) = choice.message.tool_calls {
            for tc in tool_calls {
                let input = serde_json::from_str(&tc.function.arguments)
                    .unwrap_or_else(|_| Value::Object(serde_json::Map::new()));
                content.push(ContentBlock::ToolUse {
                    id: tc.id,
                    name: tc.function.name,
                    input,
                });
            }
        }

        let stop_reason = match choice.finish_reason.as_deref() {
            Some("stop") => StopReason::EndTurn,
            Some("length") => StopReason::MaxTokens,
            Some("tool_calls") => StopReason::ToolUse,
            Some("content_filter") => StopReason::ContentFilter,
            _ => StopReason::EndTurn,
        };

        let (input_tokens, output_tokens) = match response.usage {
            Some(u) => (u.prompt_tokens, u.completion_tokens),
            None => (0, 0),
        };

        CompletionResponse {
            id: response.id,
            model: response.model,
            content,
            stop_reason,
            usage: Usage {
                input_tokens,
                output_tokens,
                cache_creation_input_tokens: 0,
                cache_read_input_tokens: 0,
            },
        }
    }

    async fn handle_error_response(&self, response: reqwest::Response) -> Error {
        let status = response.status().as_u16();

        match response.json::<OpenAIErrorResponse>().await {
            Ok(err) => {
                let error_type = err.error.error_type.as_deref().unwrap_or("unknown");
                let message = &err.error.message;

                match error_type {
                    "invalid_api_key" | "authentication_error" => Error::auth(message),
                    "rate_limit_exceeded" => Error::rate_limited(message, None),
                    "invalid_request_error" => Error::invalid_request(message),
                    "model_not_found" => Error::ModelNotFound(message.clone()),
                    "context_length_exceeded" => Error::ContextLengthExceeded(message.clone()),
                    "server_error" => Error::server(500, message),
                    _ => Error::server(status, message),
                }
            }
            Err(_) => Error::server(status, "Unknown error"),
        }
    }
}

#[async_trait]
impl Provider for OpenAICompatibleProvider {
    fn name(&self) -> &str {
        self.provider_info.name
    }

    async fn complete(&self, request: CompletionRequest) -> Result<CompletionResponse> {
        // Only require API key for remote providers
        if !self.provider_info.env_var.is_empty() {
            self.config.require_api_key()?;
        }

        let mut api_request = self.convert_request(&request);
        api_request.stream = false;

        let response = self
            .client
            .post(self.api_url())
            .json(&api_request)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        let openai_response: OpenAIResponse = response.json().await?;
        Ok(self.convert_response(openai_response))
    }

    async fn complete_stream(
        &self,
        request: CompletionRequest,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send>>> {
        if !self.provider_info.supports_streaming {
            return Err(Error::invalid_request(format!(
                "Provider {} does not support streaming",
                self.provider_info.name
            )));
        }

        // Only require API key for remote providers
        if !self.provider_info.env_var.is_empty() {
            self.config.require_api_key()?;
        }

        let mut api_request = self.convert_request(&request);
        api_request.stream = true;

        let response = self
            .client
            .post(self.api_url())
            .json(&api_request)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        let stream = parse_openai_stream(response);
        Ok(Box::pin(stream))
    }

    fn supports_tools(&self) -> bool {
        self.provider_info.supports_tools
    }

    fn supports_vision(&self) -> bool {
        self.provider_info.supports_vision
    }

    fn supports_streaming(&self) -> bool {
        self.provider_info.supports_streaming
    }

    fn default_model(&self) -> Option<&str> {
        self.provider_info.default_model
    }
}

/// Parse OpenAI SSE stream into our unified StreamChunk format.
fn parse_openai_stream(response: reqwest::Response) -> impl Stream<Item = Result<StreamChunk>> {
    use async_stream::try_stream;
    use futures::StreamExt;

    try_stream! {
        let mut event_stream = response.bytes_stream();
        let mut buffer = String::new();
        let mut tool_call_builders: std::collections::HashMap<usize, (String, String, String)> = std::collections::HashMap::new();
        let mut sent_start = false;

        while let Some(chunk) = event_stream.next().await {
            let chunk = chunk?;
            buffer.push_str(&String::from_utf8_lossy(&chunk));

            // Process complete SSE lines
            while let Some(pos) = buffer.find('\n') {
                let line = buffer[..pos].trim().to_string();
                buffer = buffer[pos + 1..].to_string();

                if line.is_empty() || !line.starts_with("data: ") {
                    continue;
                }

                let data = &line[6..]; // Skip "data: "

                if data == "[DONE]" {
                    yield StreamChunk {
                        event_type: StreamEventType::MessageStop,
                        index: None,
                        delta: None,
                        stop_reason: None,
                        usage: None,
                    };
                    continue;
                }

                if let Ok(parsed) = serde_json::from_str::<OpenAIStreamResponse>(data) {
                    if !sent_start {
                        yield StreamChunk {
                            event_type: StreamEventType::MessageStart,
                            index: None,
                            delta: None,
                            stop_reason: None,
                            usage: None,
                        };
                        sent_start = true;
                    }

                    for choice in &parsed.choices {
                        // Handle text content
                        if let Some(ref content) = choice.delta.content {
                            yield StreamChunk {
                                event_type: StreamEventType::ContentBlockDelta,
                                index: Some(0),
                                delta: Some(ContentDelta::Text { text: content.clone() }),
                                stop_reason: None,
                                usage: None,
                            };
                        }

                        // Handle tool calls
                        if let Some(ref tool_calls) = choice.delta.tool_calls {
                            for tc in tool_calls {
                                let idx = tc.index.unwrap_or(0);
                                let entry = tool_call_builders.entry(idx).or_insert_with(|| {
                                    (String::new(), String::new(), String::new())
                                });

                                if let Some(ref id) = tc.id {
                                    entry.0 = id.clone();
                                }
                                if let Some(ref func) = tc.function {
                                    if let Some(ref name) = func.name {
                                        entry.1 = name.clone();
                                    }
                                    if let Some(ref args) = func.arguments {
                                        entry.2.push_str(args);
                                    }
                                }

                                yield StreamChunk {
                                    event_type: StreamEventType::ContentBlockDelta,
                                    index: Some(idx + 1), // Offset by 1 for text block
                                    delta: Some(ContentDelta::ToolUse {
                                        id: tc.id.clone(),
                                        name: tc.function.as_ref().and_then(|f| f.name.clone()),
                                        input_json_delta: tc.function.as_ref().and_then(|f| f.arguments.clone()),
                                    }),
                                    stop_reason: None,
                                    usage: None,
                                };
                            }
                        }

                        // Handle finish reason
                        if let Some(ref reason) = choice.finish_reason {
                            let stop_reason = match reason.as_str() {
                                "stop" => StopReason::EndTurn,
                                "length" => StopReason::MaxTokens,
                                "tool_calls" => StopReason::ToolUse,
                                "content_filter" => StopReason::ContentFilter,
                                _ => StopReason::EndTurn,
                            };

                            yield StreamChunk {
                                event_type: StreamEventType::MessageDelta,
                                index: None,
                                delta: None,
                                stop_reason: Some(stop_reason),
                                usage: None,
                            };
                        }
                    }

                    // Handle usage
                    if let Some(ref usage) = parsed.usage {
                        yield StreamChunk {
                            event_type: StreamEventType::MessageDelta,
                            index: None,
                            delta: None,
                            stop_reason: None,
                            usage: Some(Usage {
                                input_tokens: usage.prompt_tokens,
                                output_tokens: usage.completion_tokens,
                                cache_creation_input_tokens: 0,
                                cache_read_input_tokens: 0,
                            }),
                        };
                    }
                }
            }
        }
    }
}

// ========== OpenAI API Types ==========

#[derive(Debug, Serialize)]
struct OpenAIRequest {
    model: String,
    messages: Vec<OpenAIMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stop: Option<Vec<String>>,
    stream: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<Vec<OpenAITool>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stream_options: Option<StreamOptions>,
}

#[derive(Debug, Serialize)]
struct StreamOptions {
    include_usage: bool,
}

#[derive(Debug, Serialize)]
struct OpenAIMessage {
    role: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    content: Option<OpenAIContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_calls: Option<Vec<OpenAIToolCall>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_call_id: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(untagged)]
enum OpenAIContent {
    Text(String),
    Parts(Vec<OpenAIContentPart>),
}

#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum OpenAIContentPart {
    Text { text: String },
    ImageUrl { image_url: ImageUrl },
}

#[derive(Debug, Serialize)]
struct ImageUrl {
    url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    detail: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
struct OpenAITool {
    #[serde(rename = "type")]
    tool_type: String,
    function: OpenAIFunction,
}

#[derive(Debug, Serialize, Deserialize)]
struct OpenAIFunction {
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    parameters: Value,
}

#[derive(Debug, Serialize, Deserialize)]
struct OpenAIToolCall {
    id: String,
    #[serde(rename = "type")]
    call_type: String,
    function: OpenAIFunctionCall,
}

#[derive(Debug, Serialize, Deserialize)]
struct OpenAIFunctionCall {
    name: String,
    arguments: String,
}

#[derive(Debug, Deserialize)]
struct OpenAIResponse {
    id: String,
    model: String,
    choices: Vec<OpenAIChoice>,
    usage: Option<OpenAIUsage>,
}

#[derive(Debug, Default, Deserialize)]
struct OpenAIChoice {
    message: OpenAIResponseMessage,
    finish_reason: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
struct OpenAIResponseMessage {
    content: Option<String>,
    tool_calls: Option<Vec<OpenAIToolCall>>,
}

#[derive(Debug, Deserialize)]
struct OpenAIStreamResponse {
    choices: Vec<OpenAIStreamChoice>,
    usage: Option<OpenAIUsage>,
}

#[derive(Debug, Deserialize)]
struct OpenAIStreamChoice {
    delta: OpenAIStreamDelta,
    finish_reason: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
struct OpenAIStreamDelta {
    content: Option<String>,
    tool_calls: Option<Vec<OpenAIStreamToolCall>>,
}

#[derive(Debug, Deserialize)]
struct OpenAIStreamToolCall {
    index: Option<usize>,
    id: Option<String>,
    function: Option<OpenAIStreamFunction>,
}

#[derive(Debug, Deserialize)]
struct OpenAIStreamFunction {
    name: Option<String>,
    arguments: Option<String>,
}

#[derive(Debug, Deserialize)]
struct OpenAIUsage {
    prompt_tokens: u32,
    completion_tokens: u32,
}

#[derive(Debug, Deserialize)]
struct OpenAIErrorResponse {
    error: OpenAIError,
}

#[derive(Debug, Deserialize)]
struct OpenAIError {
    #[serde(rename = "type")]
    error_type: Option<String>,
    message: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_provider_info() {
        assert_eq!(known_providers::TOGETHER.name, "together");
        const { assert!(known_providers::TOGETHER.supports_tools) };
        const { assert!(known_providers::DEEPSEEK.supports_streaming) };
        const { assert!(!known_providers::PERPLEXITY.supports_tools) };
    }

    #[test]
    fn test_custom_provider_creation() {
        let provider = OpenAICompatibleProvider::custom(
            "test-provider",
            "https://api.test.com/v1",
            Some("test-key".to_string()),
        )
        .unwrap();

        assert_eq!(provider.name(), "test-provider");
        assert!(provider.supports_tools());
        assert!(provider.supports_vision());
        assert!(provider.supports_streaming());
    }

    #[test]
    fn test_local_provider() {
        let provider = OpenAICompatibleProvider::lm_studio("dummy-key").unwrap();

        assert_eq!(provider.name(), "lm_studio");
        assert!(provider.api_url().contains("localhost:1234"));
    }

    #[test]
    fn test_api_url_construction() {
        // Test with trailing slash
        let provider =
            OpenAICompatibleProvider::custom("test", "https://api.test.com/v1/", None).unwrap();
        assert_eq!(
            provider.api_url(),
            "https://api.test.com/v1/chat/completions"
        );

        // Test without trailing slash
        let provider =
            OpenAICompatibleProvider::custom("test", "https://api.test.com/v1", None).unwrap();
        assert_eq!(
            provider.api_url(),
            "https://api.test.com/v1/chat/completions"
        );
    }

    #[test]
    fn test_request_conversion() {
        let provider =
            OpenAICompatibleProvider::custom("test", "https://api.test.com/v1", None).unwrap();

        let request = CompletionRequest::new("test-model", vec![Message::user("Hello")])
            .with_system("You are helpful")
            .with_max_tokens(1024);

        let openai_req = provider.convert_request(&request);

        assert_eq!(openai_req.model, "test-model");
        assert_eq!(openai_req.max_tokens, Some(1024));
        assert_eq!(openai_req.messages.len(), 2); // system + user
    }

    #[test]
    fn test_request_parameters() {
        let provider =
            OpenAICompatibleProvider::custom("test", "https://api.test.com/v1", None).unwrap();

        let request = CompletionRequest::new("test-model", vec![Message::user("Hello")])
            .with_max_tokens(500)
            .with_temperature(0.8)
            .with_top_p(0.9);

        let openai_req = provider.convert_request(&request);

        assert_eq!(openai_req.max_tokens, Some(500));
        assert_eq!(openai_req.temperature, Some(0.8));
        assert_eq!(openai_req.top_p, Some(0.9));
    }

    #[test]
    fn test_response_parsing() {
        let provider =
            OpenAICompatibleProvider::custom("test", "https://api.test.com/v1", None).unwrap();

        let openai_response = OpenAIResponse {
            id: "resp-123".to_string(),
            model: "test-model".to_string(),
            choices: vec![OpenAIChoice {
                message: OpenAIResponseMessage {
                    content: Some("Hello! How can I help?".to_string()),
                    tool_calls: None,
                },
                finish_reason: Some("stop".to_string()),
            }],
            usage: Some(OpenAIUsage {
                prompt_tokens: 10,
                completion_tokens: 20,
            }),
        };

        let response = provider.convert_response(openai_response);

        assert_eq!(response.id, "resp-123");
        assert_eq!(response.model, "test-model");
        assert_eq!(response.content.len(), 1);
        match &response.content[0] {
            ContentBlock::Text { text } => {
                assert_eq!(text, "Hello! How can I help?");
            }
            other => {
                panic!("Expected Text content block, got {:?}", other);
            }
        }
        assert!(matches!(response.stop_reason, StopReason::EndTurn));
        assert_eq!(response.usage.input_tokens, 10);
        assert_eq!(response.usage.output_tokens, 20);
    }

    #[test]
    fn test_stop_reason_mapping() {
        let provider =
            OpenAICompatibleProvider::custom("test", "https://api.test.com/v1", None).unwrap();

        // Test "stop" -> EndTurn
        let response1 = OpenAIResponse {
            id: "1".to_string(),
            model: "model".to_string(),
            choices: vec![OpenAIChoice {
                message: OpenAIResponseMessage {
                    content: Some("Done".to_string()),
                    tool_calls: None,
                },
                finish_reason: Some("stop".to_string()),
            }],
            usage: None,
        };
        assert!(matches!(
            provider.convert_response(response1).stop_reason,
            StopReason::EndTurn
        ));

        // Test "length" -> MaxTokens
        let response2 = OpenAIResponse {
            id: "2".to_string(),
            model: "model".to_string(),
            choices: vec![OpenAIChoice {
                message: OpenAIResponseMessage {
                    content: Some("Truncated...".to_string()),
                    tool_calls: None,
                },
                finish_reason: Some("length".to_string()),
            }],
            usage: None,
        };
        assert!(matches!(
            provider.convert_response(response2).stop_reason,
            StopReason::MaxTokens
        ));

        // Test "tool_calls" -> ToolUse
        let response3 = OpenAIResponse {
            id: "3".to_string(),
            model: "model".to_string(),
            choices: vec![OpenAIChoice {
                message: OpenAIResponseMessage {
                    content: None,
                    tool_calls: None,
                },
                finish_reason: Some("tool_calls".to_string()),
            }],
            usage: None,
        };
        assert!(matches!(
            provider.convert_response(response3).stop_reason,
            StopReason::ToolUse
        ));
    }

    #[test]
    fn test_tool_call_response() {
        let provider =
            OpenAICompatibleProvider::custom("test", "https://api.test.com/v1", None).unwrap();

        let openai_response = OpenAIResponse {
            id: "tool-resp-123".to_string(),
            model: "test-model".to_string(),
            choices: vec![OpenAIChoice {
                message: OpenAIResponseMessage {
                    content: None,
                    tool_calls: Some(vec![OpenAIToolCall {
                        id: "call_abc123".to_string(),
                        call_type: "function".to_string(),
                        function: OpenAIFunctionCall {
                            name: "get_weather".to_string(),
                            arguments: r#"{"location": "Paris"}"#.to_string(),
                        },
                    }]),
                },
                finish_reason: Some("tool_calls".to_string()),
            }],
            usage: None,
        };

        let response = provider.convert_response(openai_response);

        assert_eq!(response.content.len(), 1);
        assert!(matches!(response.stop_reason, StopReason::ToolUse));

        match &response.content[0] {
            ContentBlock::ToolUse { id, name, input } => {
                assert_eq!(id, "call_abc123");
                assert_eq!(name, "get_weather");
                assert_eq!(input.get("location").unwrap().as_str().unwrap(), "Paris");
            }
            other => {
                panic!("Expected ToolUse content block, got {:?}", other);
            }
        }
    }

    #[test]
    fn test_multi_turn_conversation() {
        let provider =
            OpenAICompatibleProvider::custom("test", "https://api.test.com/v1", None).unwrap();

        let request = CompletionRequest::new(
            "test-model",
            vec![
                Message::user("What is 2+2?"),
                Message::assistant("4"),
                Message::user("And 3+3?"),
            ],
        )
        .with_system("You are a math tutor");

        let openai_req = provider.convert_request(&request);

        // system + 3 user/assistant messages
        assert_eq!(openai_req.messages.len(), 4);
        assert_eq!(openai_req.messages[0].role, "system");
        assert_eq!(openai_req.messages[1].role, "user");
        assert_eq!(openai_req.messages[2].role, "assistant");
        assert_eq!(openai_req.messages[3].role, "user");
    }

    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn test_known_provider_together() {
        let _provider = OpenAICompatibleProvider::together_from_env();
        // Can't test from_env without env var, but can test the info
        assert_eq!(
            known_providers::TOGETHER.base_url,
            "https://api.together.xyz/v1"
        );
        assert!(known_providers::TOGETHER.supports_tools);
        assert!(known_providers::TOGETHER.supports_vision);
    }

    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn test_known_provider_deepseek() {
        assert_eq!(
            known_providers::DEEPSEEK.base_url,
            "https://api.deepseek.com/v1"
        );
        assert!(known_providers::DEEPSEEK.supports_tools);
        assert_eq!(
            known_providers::DEEPSEEK.default_model,
            Some("deepseek-chat")
        );
    }

    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn test_known_provider_fireworks() {
        assert_eq!(
            known_providers::FIREWORKS.base_url,
            "https://api.fireworks.ai/inference/v1"
        );
        assert!(known_providers::FIREWORKS.supports_tools);
        assert!(known_providers::FIREWORKS.supports_vision);
    }

    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn test_known_provider_local_providers() {
        // LM Studio
        assert_eq!(
            known_providers::LM_STUDIO.base_url,
            "http://localhost:1234/v1"
        );
        assert!(known_providers::LM_STUDIO.supports_tools);

        // LocalAI
        assert_eq!(
            known_providers::LOCAL_AI.base_url,
            "http://localhost:8080/v1"
        );
        assert!(known_providers::LOCAL_AI.supports_tools);

        // VLLM
        assert_eq!(known_providers::VLLM.base_url, "http://localhost:8000/v1");
        assert!(known_providers::VLLM.supports_tools);
    }

    #[test]
    fn test_from_provider_info() {
        let provider = OpenAICompatibleProvider::together("test-key").unwrap();

        assert_eq!(provider.name(), "together");
        assert!(provider.supports_tools());
        assert!(provider.supports_vision());
    }
}