Skip to content

Client

InferenceHTTPClient

HTTP client for making inference requests to Roboflow's API.

This client handles authentication, request formatting, and error handling for interacting with Roboflow's inference endpoints. It supports both synchronous and asynchronous requests.

Attributes:

Name Type Description
inference_configuration InferenceConfiguration

Configuration settings for inference requests.

client_mode HTTPClientMode

The API version mode being used (V0 or V1).

selected_model Optional[str]

Currently selected model identifier, if any.

Example
from inference_sdk import InferenceHTTPClient

client = InferenceHTTPClient(
    api_url="http://localhost:9001", # use local inference server
    # api_key="<YOUR API KEY>" # optional to access your private data and models
)

result = client.run_workflow(
    workspace_name="roboflow-docs",
    workflow_id="model-comparison",
    images={
        "image": "https://media.roboflow.com/workflows/examples/bleachers.jpg"
    },
    parameters={
        "model1": "yolov8n-640",
        "model2": "yolov11n-640"
    }
)
Source code in inference_sdk/http/client.py
 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
class InferenceHTTPClient:
    """HTTP client for making inference requests to Roboflow's API.

    This client handles authentication, request formatting, and error handling for
    interacting with Roboflow's inference endpoints. It supports both synchronous
    and asynchronous requests.

    Attributes:
        inference_configuration (InferenceConfiguration): Configuration settings for
            inference requests.
        client_mode (HTTPClientMode): The API version mode being used (V0 or V1).
        selected_model (Optional[str]): Currently selected model identifier, if any.

    Example:
        ```python
        from inference_sdk import InferenceHTTPClient

        client = InferenceHTTPClient(
            api_url="http://localhost:9001", # use local inference server
            # api_key="<YOUR API KEY>" # optional to access your private data and models
        )

        result = client.run_workflow(
            workspace_name="roboflow-docs",
            workflow_id="model-comparison",
            images={
                "image": "https://media.roboflow.com/workflows/examples/bleachers.jpg"
            },
            parameters={
                "model1": "yolov8n-640",
                "model2": "yolov11n-640"
            }
        )
        ```
    """

    @classmethod
    def init(
        cls,
        api_url: str,
        api_key: Optional[str] = None,
    ) -> "InferenceHTTPClient":
        """Initialize a new InferenceHTTPClient instance.

        Args:
            api_url (str): The base URL for the inference API.
            api_key (Optional[str], optional): API key for authentication. Defaults to None.

        Returns:
            InferenceHTTPClient: A new instance of the InferenceHTTPClient.
        """
        return cls(api_url=api_url, api_key=api_key)

    def __init__(
        self,
        api_url: str,
        api_key: Optional[str] = None,
    ):
        """Initialize a new InferenceHTTPClient instance.

        Args:
            api_url (str): The base URL for the inference API.
            api_key (Optional[str], optional): API key for authentication. Defaults to None.
        """
        self.__api_url = api_url
        self.__api_key = api_key
        self.__inference_configuration = InferenceConfiguration.init_default()
        self.__client_mode = _determine_client_mode(api_url=api_url)
        self.__selected_model: Optional[str] = None

    @property
    def inference_configuration(self) -> InferenceConfiguration:
        """Get the current inference configuration.

        Returns:
            InferenceConfiguration: The current inference configuration settings.
        """
        return self.__inference_configuration

    @property
    def client_mode(self) -> HTTPClientMode:
        """Get the current client mode.

        Returns:
            HTTPClientMode: The current API version mode (V0 or V1).
        """
        return self.__client_mode

    @property
    def selected_model(self) -> Optional[str]:
        """Get the currently selected model identifier.

        Returns:
            Optional[str]: The identifier of the currently selected model, if any.
        """
        return self.__selected_model

    @contextmanager
    def use_configuration(
        self, inference_configuration: InferenceConfiguration
    ) -> Generator["InferenceHTTPClient", None, None]:
        """Temporarily use a different inference configuration.

        Args:
            inference_configuration (InferenceConfiguration): The temporary configuration to use.

        Yields:
            Generator[InferenceHTTPClient, None, None]: The client instance with temporary configuration.
        """
        previous_configuration = self.__inference_configuration
        self.__inference_configuration = inference_configuration
        try:
            yield self
        finally:
            self.__inference_configuration = previous_configuration

    def configure(
        self, inference_configuration: InferenceConfiguration
    ) -> "InferenceHTTPClient":
        """Configure the client with new inference settings.

        Args:
            inference_configuration (InferenceConfiguration): The new configuration to apply.

        Returns:
            InferenceHTTPClient: The client instance with updated configuration.
        """
        self.__inference_configuration = inference_configuration
        return self

    def select_api_v0(self) -> "InferenceHTTPClient":
        """Select API version 0 for client operations.

        Returns:
            InferenceHTTPClient: The client instance with API v0 selected.
        """
        self.__client_mode = HTTPClientMode.V0
        return self

    def select_api_v1(self) -> "InferenceHTTPClient":
        """Select API version 1 for client operations.

        Returns:
            InferenceHTTPClient: The client instance with API v1 selected.
        """
        self.__client_mode = HTTPClientMode.V1
        return self

    @contextmanager
    def use_api_v0(self) -> Generator["InferenceHTTPClient", None, None]:
        """Temporarily use API version 0 for client operations.

        Yields:
            Generator[InferenceHTTPClient, None, None]: The client instance temporarily using API v0.
        """
        previous_client_mode = self.__client_mode
        self.__client_mode = HTTPClientMode.V0
        try:
            yield self
        finally:
            self.__client_mode = previous_client_mode

    @contextmanager
    def use_api_v1(self) -> Generator["InferenceHTTPClient", None, None]:
        """Temporarily use API version 1 for client operations.

        Yields:
            Generator[InferenceHTTPClient, None, None]: The client instance temporarily using API v1.
        """
        previous_client_mode = self.__client_mode
        self.__client_mode = HTTPClientMode.V1
        try:
            yield self
        finally:
            self.__client_mode = previous_client_mode

    def select_model(self, model_id: str) -> "InferenceHTTPClient":
        """Select a model for inference operations.

        Args:
            model_id (str): The identifier of the model to select.

        Returns:
            InferenceHTTPClient: The client instance with the selected model.
        """
        self.__selected_model = model_id
        return self

    @contextmanager
    def use_model(self, model_id: str) -> Generator["InferenceHTTPClient", None, None]:
        """Temporarily use a specific model for inference operations.

        Args:
            model_id (str): The identifier of the model to use.

        Yields:
            Generator[InferenceHTTPClient, None, None]: The client instance temporarily using the specified model.
        """
        previous_model = self.__selected_model
        self.__selected_model = model_id
        try:
            yield self
        finally:
            self.__selected_model = previous_model

    @wrap_errors
    def get_server_info(self) -> ServerInfo:
        """Get information about the inference server.

        Returns:
            ServerInfo: Information about the server configuration and status.

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        response = requests.get(f"{self.__api_url}/info")
        response.raise_for_status()
        response_payload = response.json()
        return ServerInfo.from_dict(response_payload)

    def infer_on_stream(
        self,
        input_uri: str,
        model_id: Optional[str] = None,
    ) -> Generator[Tuple[Union[str, int], np.ndarray, dict], None, None]:
        """Run inference on a video stream or sequence of images.

        Args:
            input_uri (str): URI of the input stream or directory.
            model_id (Optional[str], optional): Model identifier to use for inference. Defaults to None.

        Yields:
            Generator[Tuple[Union[str, int], np.ndarray, dict], None, None]: Tuples of (frame reference, frame data, prediction).
        """
        for reference, frame in load_stream_inference_input(
            input_uri=input_uri,
            image_extensions=self.__inference_configuration.image_extensions_for_directory_scan,
        ):
            prediction = self.infer(
                inference_input=frame,
                model_id=model_id,
            )
            yield reference, frame, prediction

    @wrap_errors
    def infer(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        model_id: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Run inference on one or more images.

        Args:
            inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for inference.
            model_id (Optional[str], optional): Model identifier to use for inference. Defaults to None.

        Returns:
            Union[dict, List[dict]]: Inference results for the input image(s).

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        if self.__client_mode is HTTPClientMode.V0:
            return self.infer_from_api_v0(
                inference_input=inference_input,
                model_id=model_id,
            )
        return self.infer_from_api_v1(
            inference_input=inference_input,
            model_id=model_id,
        )

    @wrap_errors_async
    async def infer_async(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        model_id: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Run inference asynchronously on one or more images.

        Args:
            inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for inference.
            model_id (Optional[str], optional): Model identifier to use for inference. Defaults to None.

        Returns:
            Union[dict, List[dict]]: Inference results for the input image(s).

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        if self.__client_mode is HTTPClientMode.V0:
            return await self.infer_from_api_v0_async(
                inference_input=inference_input,
                model_id=model_id,
            )
        return await self.infer_from_api_v1_async(
            inference_input=inference_input,
            model_id=model_id,
        )

    def infer_from_api_v0(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        model_id: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Run inference using API v0.

        Args:
            inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for inference.
            model_id (Optional[str], optional): Model identifier to use for inference. Defaults to None.

        Returns:
            Union[dict, List[dict]]: Inference results for the input image(s).

        Raises:
            ModelNotSelectedError: If no model is selected.
            APIKeyNotProvided: If API key is required but not provided.
            InvalidModelIdentifier: If the model identifier format is invalid.
        """
        model_id_to_be_used = model_id or self.__selected_model
        _ensure_model_is_selected(model_id=model_id_to_be_used)
        _ensure_api_key_provided(api_key=self.__api_key)
        model_id_to_be_used = resolve_roboflow_model_alias(model_id=model_id_to_be_used)
        model_id_chunks = model_id_to_be_used.split("/")
        if len(model_id_chunks) != 2:
            raise InvalidModelIdentifier(
                f"Invalid model id: {model_id}. Expected format: project_id/model_version_id."
            )
        max_height, max_width = _determine_client_downsizing_parameters(
            client_downsizing_disabled=self.__inference_configuration.client_downsizing_disabled,
            model_description=None,
            default_max_input_size=self.__inference_configuration.default_max_input_size,
        )
        encoded_inference_inputs = load_static_inference_input(
            inference_input=inference_input,
            max_height=max_height,
            max_width=max_width,
        )
        params = {
            "api_key": self.__api_key,
        }
        params.update(self.__inference_configuration.to_legacy_call_parameters())
        requests_data = prepare_requests_data(
            url=f"{self.__api_url}/{model_id_chunks[0]}/{model_id_chunks[1]}",
            encoded_inference_inputs=encoded_inference_inputs,
            headers=DEFAULT_HEADERS,
            parameters=params,
            payload=None,
            max_batch_size=1,
            image_placement=ImagePlacement.DATA,
        )
        responses = execute_requests_packages(
            requests_data=requests_data,
            request_method=RequestMethod.POST,
            max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
        )
        results = []
        for request_data, response in zip(requests_data, responses):
            if response_contains_jpeg_image(response=response):
                visualisation = transform_visualisation_bytes(
                    visualisation=response.content,
                    expected_format=self.__inference_configuration.output_visualisation_format,
                )
                parsed_response = {"visualization": visualisation}
            else:
                parsed_response = response.json()
                if parsed_response.get("visualization") is not None:
                    parsed_response["visualization"] = transform_base64_visualisation(
                        visualisation=parsed_response["visualization"],
                        expected_format=self.__inference_configuration.output_visualisation_format,
                    )
            parsed_response = adjust_prediction_to_client_scaling_factor(
                prediction=parsed_response,
                scaling_factor=request_data.image_scaling_factors[0],
            )
            results.append(parsed_response)
        return unwrap_single_element_list(sequence=results)

    async def infer_from_api_v0_async(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        model_id: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Run inference using API v0 asynchronously.

        Args:
            inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for inference.
            model_id (Optional[str], optional): Model identifier to use for inference. Defaults to None.

        Returns:
            Union[dict, List[dict]]: Inference results for the input image(s).

        Raises:
            ModelNotSelectedError: If no model is selected.
            APIKeyNotProvided: If API key is required but not provided.
            InvalidModelIdentifier: If the model identifier format is invalid.
        """
        model_id_to_be_used = model_id or self.__selected_model
        _ensure_model_is_selected(model_id=model_id_to_be_used)
        _ensure_api_key_provided(api_key=self.__api_key)
        model_id_to_be_used = resolve_roboflow_model_alias(model_id=model_id_to_be_used)
        model_id_chunks = model_id_to_be_used.split("/")
        if len(model_id_chunks) != 2:
            raise InvalidModelIdentifier(
                f"Invalid model id: {model_id}. Expected format: project_id/model_version_id."
            )
        max_height, max_width = _determine_client_downsizing_parameters(
            client_downsizing_disabled=self.__inference_configuration.client_downsizing_disabled,
            model_description=None,
            default_max_input_size=self.__inference_configuration.default_max_input_size,
        )
        encoded_inference_inputs = await load_static_inference_input_async(
            inference_input=inference_input,
            max_height=max_height,
            max_width=max_width,
        )
        params = {
            "api_key": self.__api_key,
        }
        params.update(self.__inference_configuration.to_legacy_call_parameters())
        requests_data = prepare_requests_data(
            url=f"{self.__api_url}/{model_id_chunks[0]}/{model_id_chunks[1]}",
            encoded_inference_inputs=encoded_inference_inputs,
            headers=DEFAULT_HEADERS,
            parameters=params,
            payload=None,
            max_batch_size=1,
            image_placement=ImagePlacement.DATA,
        )
        responses = await execute_requests_packages_async(
            requests_data=requests_data,
            request_method=RequestMethod.POST,
            max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
        )
        results = []
        for request_data, response in zip(requests_data, responses):
            if not issubclass(type(response), dict):
                visualisation = transform_visualisation_bytes(
                    visualisation=response,
                    expected_format=self.__inference_configuration.output_visualisation_format,
                )
                parsed_response = {"visualization": visualisation}
            else:
                parsed_response = response
                if parsed_response.get("visualization") is not None:
                    parsed_response["visualization"] = transform_base64_visualisation(
                        visualisation=parsed_response["visualization"],
                        expected_format=self.__inference_configuration.output_visualisation_format,
                    )
            parsed_response = adjust_prediction_to_client_scaling_factor(
                prediction=parsed_response,
                scaling_factor=request_data.image_scaling_factors[0],
            )
            results.append(parsed_response)
        return unwrap_single_element_list(sequence=results)

    def infer_from_api_v1(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        model_id: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        self.__ensure_v1_client_mode()
        model_id_to_be_used = model_id or self.__selected_model
        _ensure_model_is_selected(model_id=model_id_to_be_used)
        model_id_to_be_used = resolve_roboflow_model_alias(model_id=model_id_to_be_used)
        model_description = self.get_model_description(model_id=model_id_to_be_used)
        max_height, max_width = _determine_client_downsizing_parameters(
            client_downsizing_disabled=self.__inference_configuration.client_downsizing_disabled,
            model_description=model_description,
            default_max_input_size=self.__inference_configuration.default_max_input_size,
        )
        if model_description.task_type not in NEW_INFERENCE_ENDPOINTS:
            raise ModelTaskTypeNotSupportedError(
                f"Model task {model_description.task_type} is not supported by API v1 client."
            )
        encoded_inference_inputs = load_static_inference_input(
            inference_input=inference_input,
            max_height=max_height,
            max_width=max_width,
        )
        payload = {
            "api_key": self.__api_key,
            "model_id": model_id_to_be_used,
        }
        endpoint = NEW_INFERENCE_ENDPOINTS[model_description.task_type]
        payload.update(
            self.__inference_configuration.to_api_call_parameters(
                client_mode=self.__client_mode,
                task_type=model_description.task_type,
            )
        )
        requests_data = prepare_requests_data(
            url=f"{self.__api_url}{endpoint}",
            encoded_inference_inputs=encoded_inference_inputs,
            headers=DEFAULT_HEADERS,
            parameters=None,
            payload=payload,
            max_batch_size=self.__inference_configuration.max_batch_size,
            image_placement=ImagePlacement.JSON,
        )
        responses = execute_requests_packages(
            requests_data=requests_data,
            request_method=RequestMethod.POST,
            max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
        )
        results = []
        for request_data, response in zip(requests_data, responses):
            parsed_response = response.json()
            if not issubclass(type(parsed_response), list):
                parsed_response = [parsed_response]
            for parsed_response_element, scaling_factor in zip(
                parsed_response, request_data.image_scaling_factors
            ):
                if parsed_response_element.get("visualization") is not None:
                    parsed_response_element["visualization"] = (
                        transform_base64_visualisation(
                            visualisation=parsed_response_element["visualization"],
                            expected_format=self.__inference_configuration.output_visualisation_format,
                        )
                    )
                parsed_response_element = adjust_prediction_to_client_scaling_factor(
                    prediction=parsed_response_element,
                    scaling_factor=scaling_factor,
                )
                results.append(parsed_response_element)
        return unwrap_single_element_list(sequence=results)

    async def infer_from_api_v1_async(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        model_id: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        self.__ensure_v1_client_mode()
        model_id_to_be_used = model_id or self.__selected_model
        _ensure_model_is_selected(model_id=model_id_to_be_used)
        model_id_to_be_used = resolve_roboflow_model_alias(model_id=model_id_to_be_used)
        model_description = await self.get_model_description_async(
            model_id=model_id_to_be_used
        )
        max_height, max_width = _determine_client_downsizing_parameters(
            client_downsizing_disabled=self.__inference_configuration.client_downsizing_disabled,
            model_description=model_description,
            default_max_input_size=self.__inference_configuration.default_max_input_size,
        )
        if model_description.task_type not in NEW_INFERENCE_ENDPOINTS:
            raise ModelTaskTypeNotSupportedError(
                f"Model task {model_description.task_type} is not supported by API v1 client."
            )
        encoded_inference_inputs = await load_static_inference_input_async(
            inference_input=inference_input,
            max_height=max_height,
            max_width=max_width,
        )
        payload = {
            "api_key": self.__api_key,
            "model_id": model_id_to_be_used,
        }
        endpoint = NEW_INFERENCE_ENDPOINTS[model_description.task_type]
        payload.update(
            self.__inference_configuration.to_api_call_parameters(
                client_mode=self.__client_mode,
                task_type=model_description.task_type,
            )
        )
        requests_data = prepare_requests_data(
            url=f"{self.__api_url}{endpoint}",
            encoded_inference_inputs=encoded_inference_inputs,
            headers=DEFAULT_HEADERS,
            parameters=None,
            payload=payload,
            max_batch_size=self.__inference_configuration.max_batch_size,
            image_placement=ImagePlacement.JSON,
        )
        responses = await execute_requests_packages_async(
            requests_data=requests_data,
            request_method=RequestMethod.POST,
            max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
        )
        results = []
        for request_data, parsed_response in zip(requests_data, responses):
            if not issubclass(type(parsed_response), list):
                parsed_response = [parsed_response]
            for parsed_response_element, scaling_factor in zip(
                parsed_response, request_data.image_scaling_factors
            ):
                if parsed_response_element.get("visualization") is not None:
                    parsed_response_element["visualization"] = (
                        transform_base64_visualisation(
                            visualisation=parsed_response_element["visualization"],
                            expected_format=self.__inference_configuration.output_visualisation_format,
                        )
                    )
                parsed_response_element = adjust_prediction_to_client_scaling_factor(
                    prediction=parsed_response_element,
                    scaling_factor=scaling_factor,
                )
                results.append(parsed_response_element)
        return unwrap_single_element_list(sequence=results)

    def get_model_description(
        self, model_id: str, allow_loading: bool = True
    ) -> ModelDescription:
        """Get the description of a model.

        Args:
            model_id (str): The identifier of the model.
            allow_loading (bool, optional): Whether to load the model if not already loaded. Defaults to True.

        Returns:
            ModelDescription: Description of the model.

        Raises:
            WrongClientModeError: If not in API v1 mode.
            ModelNotInitializedError: If the model is not initialized and cannot be loaded.
        """
        self.__ensure_v1_client_mode()
        de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
        registered_models = self.list_loaded_models()
        matching_model = filter_model_descriptions(
            descriptions=registered_models.models,
            model_id=de_aliased_model_id,
        )
        if matching_model is None and allow_loading is True:
            registered_models = self.load_model(model_id=de_aliased_model_id)
            matching_model = filter_model_descriptions(
                descriptions=registered_models.models,
                model_id=de_aliased_model_id,
            )
        if matching_model is not None:
            return matching_model
        raise ModelNotInitializedError(
            f"Model {model_id} (de-aliased: {de_aliased_model_id}) is not initialised and cannot "
            f"retrieve its description."
        )

    async def get_model_description_async(
        self, model_id: str, allow_loading: bool = True
    ) -> ModelDescription:
        """Get the description of a model asynchronously.

        Args:
            model_id (str): The identifier of the model.
            allow_loading (bool, optional): Whether to load the model if not already loaded. Defaults to True.

        Returns:
            ModelDescription: Description of the model.

        Raises:
            WrongClientModeError: If not in API v1 mode.
            ModelNotInitializedError: If the model is not initialized and cannot be loaded.
        """
        self.__ensure_v1_client_mode()
        de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
        registered_models = await self.list_loaded_models_async()
        matching_model = filter_model_descriptions(
            descriptions=registered_models.models,
            model_id=de_aliased_model_id,
        )
        if matching_model is None and allow_loading is True:
            registered_models = await self.load_model_async(
                model_id=de_aliased_model_id
            )
            matching_model = filter_model_descriptions(
                descriptions=registered_models.models,
                model_id=de_aliased_model_id,
            )
        if matching_model is not None:
            return matching_model
        raise ModelNotInitializedError(
            f"Model {model_id} (de-aliased: {de_aliased_model_id}) is not initialised and cannot "
            f"retrieve its description."
        )

    @wrap_errors
    def list_loaded_models(self) -> RegisteredModels:
        """List all models currently loaded on the server.

        Returns:
            RegisteredModels: Information about registered models.

        Raises:
            WrongClientModeError: If not in API v1 mode.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        self.__ensure_v1_client_mode()
        response = requests.get(f"{self.__api_url}/model/registry")
        response.raise_for_status()
        response_payload = response.json()
        return RegisteredModels.from_dict(response_payload)

    @wrap_errors_async
    async def list_loaded_models_async(self) -> RegisteredModels:
        """List all models currently loaded on the server asynchronously.

        Returns:
            RegisteredModels: Information about registered models.

        Raises:
            WrongClientModeError: If not in API v1 mode.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        self.__ensure_v1_client_mode()
        async with aiohttp.ClientSession() as session:
            async with session.get(f"{self.__api_url}/model/registry") as response:
                response.raise_for_status()
                response_payload = await response.json()
                return RegisteredModels.from_dict(response_payload)

    @wrap_errors
    def load_model(
        self, model_id: str, set_as_default: bool = False
    ) -> RegisteredModels:
        """Load a model onto the server.

        Args:
            model_id (str): The identifier of the model to load.
            set_as_default (bool, optional): Whether to set this model as the default. Defaults to False.

        Returns:
            RegisteredModels: Updated information about registered models.

        Raises:
            WrongClientModeError: If not in API v1 mode.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        self.__ensure_v1_client_mode()
        de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
        response = requests.post(
            f"{self.__api_url}/model/add",
            json={
                "model_id": de_aliased_model_id,
                "api_key": self.__api_key,
            },
            headers=DEFAULT_HEADERS,
        )
        response.raise_for_status()
        response_payload = response.json()
        if set_as_default:
            self.__selected_model = de_aliased_model_id
        return RegisteredModels.from_dict(response_payload)

    @wrap_errors_async
    async def load_model_async(
        self, model_id: str, set_as_default: bool = False
    ) -> RegisteredModels:
        """Load a model onto the server asynchronously.

        Args:
            model_id (str): The identifier of the model to load.
            set_as_default (bool, optional): Whether to set this model as the default. Defaults to False.

        Returns:
            RegisteredModels: Updated information about registered models.

        Raises:
            WrongClientModeError: If not in API v1 mode.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        self.__ensure_v1_client_mode()
        de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
        payload = {
            "model_id": de_aliased_model_id,
            "api_key": self.__api_key,
        }
        async with aiohttp.ClientSession() as session:
            async with session.post(
                f"{self.__api_url}/model/add",
                json=payload,
                headers=DEFAULT_HEADERS,
            ) as response:
                response.raise_for_status()
                response_payload = await response.json()
        if set_as_default:
            self.__selected_model = de_aliased_model_id
        return RegisteredModels.from_dict(response_payload)

    @wrap_errors
    def unload_model(self, model_id: str) -> RegisteredModels:
        """Unload a model from the server.

        Args:
            model_id (str): The identifier of the model to unload.

        Returns:
            RegisteredModels: Updated information about registered models.

        Raises:
            WrongClientModeError: If not in API v1 mode.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        self.__ensure_v1_client_mode()
        de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
        response = requests.post(
            f"{self.__api_url}/model/remove",
            json={
                "model_id": de_aliased_model_id,
            },
            headers=DEFAULT_HEADERS,
        )
        response.raise_for_status()
        response_payload = response.json()
        if (
            de_aliased_model_id == self.__selected_model
            or model_id == self.__selected_model
        ):
            self.__selected_model = None
        return RegisteredModels.from_dict(response_payload)

    @wrap_errors_async
    async def unload_model_async(self, model_id: str) -> RegisteredModels:
        self.__ensure_v1_client_mode()
        de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
        async with aiohttp.ClientSession() as session:
            async with session.post(
                f"{self.__api_url}/model/remove",
                json={
                    "model_id": de_aliased_model_id,
                },
                headers=DEFAULT_HEADERS,
            ) as response:
                response.raise_for_status()
                response_payload = await response.json()
        if (
            de_aliased_model_id == self.__selected_model
            or model_id == self.__selected_model
        ):
            self.__selected_model = None
        return RegisteredModels.from_dict(response_payload)

    @wrap_errors
    def unload_all_models(self) -> RegisteredModels:
        self.__ensure_v1_client_mode()
        response = requests.post(f"{self.__api_url}/model/clear")
        response.raise_for_status()
        response_payload = response.json()
        self.__selected_model = None
        return RegisteredModels.from_dict(response_payload)

    @wrap_errors_async
    async def unload_all_models_async(self) -> RegisteredModels:
        self.__ensure_v1_client_mode()
        async with aiohttp.ClientSession() as session:
            async with session.post(f"{self.__api_url}/model/clear") as response:
                response.raise_for_status()
                response_payload = await response.json()
        self.__selected_model = None
        return RegisteredModels.from_dict(response_payload)

    @wrap_errors
    def prompt_cogvlm(
        self,
        visual_prompt: ImagesReference,
        text_prompt: str,
        chat_history: Optional[List[Tuple[str, str]]] = None,
    ) -> dict:
        self.__ensure_v1_client_mode()  # Lambda does not support CogVLM, so we require v1 mode of client
        encoded_image = load_static_inference_input(
            inference_input=visual_prompt,
        )
        payload = {
            "api_key": self.__api_key,
            "model_id": "cogvlm",
            "prompt": text_prompt,
        }
        payload = inject_images_into_payload(
            payload=payload,
            encoded_images=encoded_image,
        )
        if chat_history is not None:
            payload["history"] = chat_history
        response = requests.post(
            f"{self.__api_url}/llm/cogvlm",
            json=payload,
            headers=DEFAULT_HEADERS,
        )
        api_key_safe_raise_for_status(response=response)
        return response.json()

    @wrap_errors_async
    async def prompt_cogvlm_async(
        self,
        visual_prompt: ImagesReference,
        text_prompt: str,
        chat_history: Optional[List[Tuple[str, str]]] = None,
    ) -> dict:
        self.__ensure_v1_client_mode()  # Lambda does not support CogVLM, so we require v1 mode of client
        encoded_image = await load_static_inference_input_async(
            inference_input=visual_prompt,
        )
        payload = {
            "api_key": self.__api_key,
            "model_id": "cogvlm",
            "prompt": text_prompt,
        }
        payload = inject_images_into_payload(
            payload=payload,
            encoded_images=encoded_image,
        )
        if chat_history is not None:
            payload["history"] = chat_history
        async with aiohttp.ClientSession() as session:
            async with session.post(
                f"{self.__api_url}/llm/cogvlm",
                json=payload,
                headers=DEFAULT_HEADERS,
            ) as response:
                response.raise_for_status()
                return await response.json()

    @wrap_errors
    def ocr_image(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        model: str = "doctr",
        version: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Run OCR on input image(s).

        Args:
            inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for OCR.
            model (str, optional): OCR model to use ('doctr' or 'trocr'). Defaults to "doctr".
            version (Optional[str], optional): Model version to use. Defaults to None.
                For trocr, supported versions are: 'trocr-small-printed', 'trocr-base-printed', 'trocr-large-printed'.

        Returns:
            Union[dict, List[dict]]: OCR results for the input image(s).

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        encoded_inference_inputs = load_static_inference_input(
            inference_input=inference_input,
        )
        payload = self.__initialise_payload()
        if version:
            key = f"{model.lower()}_version_id"
            payload[key] = version
        model_path = resolve_ocr_path(model_name=model)
        url = self.__wrap_url_with_api_key(f"{self.__api_url}{model_path}")
        requests_data = prepare_requests_data(
            url=url,
            encoded_inference_inputs=encoded_inference_inputs,
            headers=DEFAULT_HEADERS,
            parameters=None,
            payload=payload,
            max_batch_size=1,
            image_placement=ImagePlacement.JSON,
        )
        responses = execute_requests_packages(
            requests_data=requests_data,
            request_method=RequestMethod.POST,
            max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
        )
        results = [r.json() for r in responses]
        return unwrap_single_element_list(sequence=results)

    @wrap_errors_async
    async def ocr_image_async(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        model: str = "doctr",
        version: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Run OCR on input image(s) asynchronously.

        Args:
            inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for OCR.
            model (str, optional): OCR model to use ('doctr' or 'trocr'). Defaults to "doctr".
            version (Optional[str], optional): Model version to use. Defaults to None.
                For trocr, supported versions are: 'trocr-small-printed', 'trocr-base-printed', 'trocr-large-printed'.

        Returns:
            Union[dict, List[dict]]: OCR results for the input image(s).

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        encoded_inference_inputs = await load_static_inference_input_async(
            inference_input=inference_input,
        )
        payload = self.__initialise_payload()
        if version:
            key = f"{model.lower()}_version_id"
            payload[key] = version
        model_path = resolve_ocr_path(model_name=model)
        url = self.__wrap_url_with_api_key(f"{self.__api_url}{model_path}")
        requests_data = prepare_requests_data(
            url=url,
            encoded_inference_inputs=encoded_inference_inputs,
            headers=DEFAULT_HEADERS,
            parameters=None,
            payload=payload,
            max_batch_size=1,
            image_placement=ImagePlacement.JSON,
        )
        responses = await execute_requests_packages_async(
            requests_data=requests_data,
            request_method=RequestMethod.POST,
            max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
        )
        return unwrap_single_element_list(sequence=responses)

    @wrap_errors
    def detect_gazes(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
    ) -> Union[dict, List[dict]]:
        """Detect gazes in input image(s).

        Args:
            inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for gaze detection.

        Returns:
            Union[dict, List[dict]]: Gaze detection results for the input image(s).

        Raises:
            WrongClientModeError: If not in API v1 mode.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        self.__ensure_v1_client_mode()  # Lambda does not support Gaze, so we require v1 mode of client
        result = self._post_images(
            inference_input=inference_input, endpoint="/gaze/gaze_detection"
        )
        return combine_gaze_detections(detections=result)

    @wrap_errors_async
    async def detect_gazes_async(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
    ) -> Union[dict, List[dict]]:
        """Detect gazes in input image(s) asynchronously.

        Args:
            inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for gaze detection.

        Returns:
            Union[dict, List[dict]]: Gaze detection results for the input image(s).

        Raises:
            WrongClientModeError: If not in API v1 mode.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        self.__ensure_v1_client_mode()  # Lambda does not support Gaze, so we require v1 mode of client
        result = await self._post_images_async(
            inference_input=inference_input, endpoint="/gaze/gaze_detection"
        )
        return combine_gaze_detections(detections=result)

    @wrap_errors
    def get_clip_image_embeddings(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        clip_version: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Get CLIP embeddings for input image(s).

        Args:
            inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) to embed.
            clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

        Returns:
            Union[dict, List[dict]]: CLIP embeddings for the input image(s).

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        extra_payload = {}
        if clip_version is not None:
            extra_payload["clip_version_id"] = clip_version
        result = self._post_images(
            inference_input=inference_input,
            endpoint="/clip/embed_image",
            extra_payload=extra_payload,
        )
        result = combine_clip_embeddings(embeddings=result)
        return unwrap_single_element_list(result)

    @wrap_errors_async
    async def get_clip_image_embeddings_async(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        clip_version: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Get CLIP embeddings for input image(s) asynchronously.

        Args:
            inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) to embed.
            clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

        Returns:
            Union[dict, List[dict]]: CLIP embeddings for the input image(s).

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        extra_payload = {}
        if clip_version is not None:
            extra_payload["clip_version_id"] = clip_version
        result = await self._post_images_async(
            inference_input=inference_input,
            endpoint="/clip/embed_image",
            extra_payload=extra_payload,
        )
        result = combine_clip_embeddings(embeddings=result)
        return unwrap_single_element_list(result)

    @wrap_errors
    def get_clip_text_embeddings(
        self,
        text: Union[str, List[str]],
        clip_version: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Get CLIP embeddings for input text(s).

        Args:
            text (Union[str, List[str]]): Input text(s) to embed.
            clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

        Returns:
            Union[dict, List[dict]]: CLIP embeddings for the input text(s).

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        payload = self.__initialise_payload()
        payload["text"] = text
        if clip_version is not None:
            payload["clip_version_id"] = clip_version
        response = requests.post(
            self.__wrap_url_with_api_key(f"{self.__api_url}/clip/embed_text"),
            json=payload,
            headers=DEFAULT_HEADERS,
        )
        api_key_safe_raise_for_status(response=response)
        return unwrap_single_element_list(sequence=response.json())

    @wrap_errors_async
    async def get_clip_text_embeddings_async(
        self,
        text: Union[str, List[str]],
        clip_version: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Get CLIP embeddings for input text(s) asynchronously.

        Args:
            text (Union[str, List[str]]): Input text(s) to embed.
            clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

        Returns:
            Union[dict, List[dict]]: CLIP embeddings for the input text(s).

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        payload = self.__initialise_payload()
        payload["text"] = text
        if clip_version is not None:
            payload["clip_version_id"] = clip_version
        async with aiohttp.ClientSession() as session:
            async with session.post(
                self.__wrap_url_with_api_key(f"{self.__api_url}/clip/embed_text"),
                json=payload,
                headers=DEFAULT_HEADERS,
            ) as response:
                response.raise_for_status()
                response_payload = await response.json()
        return unwrap_single_element_list(sequence=response_payload)

    @wrap_errors
    def clip_compare(
        self,
        subject: Union[str, ImagesReference],
        prompt: Union[str, List[str], ImagesReference, List[ImagesReference]],
        subject_type: str = "image",
        prompt_type: str = "text",
        clip_version: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Compare a subject against prompts using CLIP embeddings.

        Args:
            subject (Union[str, ImagesReference]): The subject to compare (image or text).
            prompt (Union[str, List[str], ImagesReference, List[ImagesReference]]): The prompt(s) to compare against.
            subject_type (str, optional): Type of subject ('image' or 'text'). Defaults to "image".
            prompt_type (str, optional): Type of prompt(s) ('image' or 'text'). Defaults to "text".
            clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

        Returns:
            Union[dict, List[dict]]: Comparison results between subject and prompt(s).

        Raises:
            InvalidParameterError: If subject_type or prompt_type is invalid.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        if (
            subject_type not in CLIP_ARGUMENT_TYPES
            or prompt_type not in CLIP_ARGUMENT_TYPES
        ):
            raise InvalidParameterError(
                f"Could not accept `subject_type` and `prompt_type` with values different than {CLIP_ARGUMENT_TYPES}"
            )
        payload = self.__initialise_payload()
        payload["subject_type"] = subject_type
        payload["prompt_type"] = prompt_type
        if clip_version is not None:
            payload["clip_version_id"] = clip_version
        if subject_type == "image":
            encoded_image = load_static_inference_input(
                inference_input=subject,
            )
            payload = inject_images_into_payload(
                payload=payload, encoded_images=encoded_image, key="subject"
            )
        else:
            payload["subject"] = subject
        if prompt_type == "image":
            encoded_inference_inputs = load_static_inference_input(
                inference_input=prompt,
            )
            payload = inject_images_into_payload(
                payload=payload, encoded_images=encoded_inference_inputs, key="prompt"
            )
        else:
            payload["prompt"] = prompt
        response = requests.post(
            self.__wrap_url_with_api_key(f"{self.__api_url}/clip/compare"),
            json=payload,
            headers=DEFAULT_HEADERS,
        )
        api_key_safe_raise_for_status(response=response)
        return response.json()

    @wrap_errors_async
    async def clip_compare_async(
        self,
        subject: Union[str, ImagesReference],
        prompt: Union[str, List[str], ImagesReference, List[ImagesReference]],
        subject_type: str = "image",
        prompt_type: str = "text",
        clip_version: Optional[str] = None,
    ) -> Union[dict, List[dict]]:
        """Compare a subject against prompts using CLIP embeddings asynchronously.

        Args:
            subject (Union[str, ImagesReference]): The subject to compare (image or text).
            prompt (Union[str, List[str], ImagesReference, List[ImagesReference]]): The prompt(s) to compare against.
            subject_type (str, optional): Type of subject ('image' or 'text'). Defaults to "image".
            prompt_type (str, optional): Type of prompt(s) ('image' or 'text'). Defaults to "text".
            clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

        Returns:
            Union[dict, List[dict]]: Comparison results between subject and prompt(s).

        Raises:
            InvalidParameterError: If subject_type or prompt_type is invalid.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        if (
            subject_type not in CLIP_ARGUMENT_TYPES
            or prompt_type not in CLIP_ARGUMENT_TYPES
        ):
            raise InvalidParameterError(
                f"Could not accept `subject_type` and `prompt_type` with values different than {CLIP_ARGUMENT_TYPES}"
            )
        payload = self.__initialise_payload()
        payload["subject_type"] = subject_type
        payload["prompt_type"] = prompt_type
        if clip_version is not None:
            payload["clip_version_id"] = clip_version
        if subject_type == "image":
            encoded_image = await load_static_inference_input_async(
                inference_input=subject,
            )
            payload = inject_images_into_payload(
                payload=payload, encoded_images=encoded_image, key="subject"
            )
        else:
            payload["subject"] = subject
        if prompt_type == "image":
            encoded_inference_inputs = await load_static_inference_input_async(
                inference_input=prompt,
            )
            payload = inject_images_into_payload(
                payload=payload, encoded_images=encoded_inference_inputs, key="prompt"
            )
        else:
            payload["prompt"] = prompt

        async with aiohttp.ClientSession() as session:
            async with session.post(
                self.__wrap_url_with_api_key(f"{self.__api_url}/clip/compare"),
                json=payload,
                headers=DEFAULT_HEADERS,
            ) as response:
                response.raise_for_status()
                return await response.json()

    @deprecated(
        reason="Please use run_workflow(...) method. This method will be removed end of Q2 2024"
    )
    @wrap_errors
    def infer_from_workflow(
        self,
        workspace_name: Optional[str] = None,
        workflow_name: Optional[str] = None,
        specification: Optional[dict] = None,
        images: Optional[Dict[str, Any]] = None,
        parameters: Optional[Dict[str, Any]] = None,
        excluded_fields: Optional[List[str]] = None,
        use_cache: bool = True,
        enable_profiling: bool = False,
    ) -> List[Dict[str, Any]]:
        """Run inference using a workflow specification.

        Triggers inference from workflow specification at the inference HTTP
        side. Either (`workspace_name` and `workflow_name`) or `workflow_specification` must be
        provided. In the first case - definition of workflow will be fetched
        from Roboflow API, in the latter - `workflow_specification` will be
        used. `images` and `parameters` will be merged into workflow inputs,
        the distinction is made to make sure the SDK can easily serialise
        images and prepare a proper payload. Supported images are numpy arrays,
        PIL.Image and base64 images, links to images and local paths.
        `excluded_fields` will be added to request to filter out results
        of workflow execution at the server side.

        Args:
            workspace_name (Optional[str], optional): Name of the workspace containing the workflow. Defaults to None.
            workflow_name (Optional[str], optional): Name of the workflow. Defaults to None.
            specification (Optional[dict], optional): Direct workflow specification. Defaults to None.
            images (Optional[Dict[str, Any]], optional): Images to process. Defaults to None.
            parameters (Optional[Dict[str, Any]], optional): Additional parameters for the workflow. Defaults to None.
            excluded_fields (Optional[List[str]], optional): Fields to exclude from results. Defaults to None.
            use_cache (bool, optional): Whether to use cached results. Defaults to True.
            enable_profiling (bool, optional): Whether to enable profiling. Defaults to False.

        Returns:
            List[Dict[str, Any]]: Results of the workflow execution.

        Raises:
            InvalidParameterError: If neither workflow identifiers nor specification is provided.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        return self._run_workflow(
            workspace_name=workspace_name,
            workflow_id=workflow_name,
            specification=specification,
            images=images,
            parameters=parameters,
            excluded_fields=excluded_fields,
            legacy_endpoints=True,
            use_cache=use_cache,
            enable_profiling=enable_profiling,
        )

    @wrap_errors
    def run_workflow(
        self,
        workspace_name: Optional[str] = None,
        workflow_id: Optional[str] = None,
        specification: Optional[dict] = None,
        images: Optional[Dict[str, Any]] = None,
        parameters: Optional[Dict[str, Any]] = None,
        excluded_fields: Optional[List[str]] = None,
        use_cache: bool = True,
        enable_profiling: bool = False,
    ) -> List[Dict[str, Any]]:
        """Run inference using a workflow specification.

        Triggers inference from workflow specification at the inference HTTP
        side. Either (`workspace_name` and `workflow_id`) or `workflow_specification` must be
        provided. In the first case - definition of workflow will be fetched
        from Roboflow API, in the latter - `workflow_specification` will be
        used. `images` and `parameters` will be merged into workflow inputs,
        the distinction is made to make sure the SDK can easily serialise
        images and prepare a proper payload. Supported images are numpy arrays,
        PIL.Image and base64 images, links to images and local paths.
        `excluded_fields` will be added to request to filter out results
        of workflow execution at the server side.

        **Important!**
        Method is not compatible with inference server <=0.9.18. Please migrate to newer version of
        the server before end of Q2 2024. Until that is done - use old method: infer_from_workflow(...).

        Note:
            Method is not compatible with inference server <=0.9.18. Please migrate to newer version of
            the server before end of Q2 2024. Until that is done - use old method: infer_from_workflow(...).

        Args:
            workspace_name (Optional[str], optional): Name of the workspace containing the workflow. Defaults to None.
            workflow_id (Optional[str], optional): ID of the workflow. Defaults to None.
            specification (Optional[dict], optional): Direct workflow specification. Defaults to None.
            images (Optional[Dict[str, Any]], optional): Images to process. Defaults to None.
            parameters (Optional[Dict[str, Any]], optional): Additional parameters for the workflow. Defaults to None.
            excluded_fields (Optional[List[str]], optional): Fields to exclude from results. Defaults to None.
            use_cache (bool, optional): Whether to use cached results. Defaults to True.
            enable_profiling (bool, optional): Whether to enable profiling. Defaults to False.

        Returns:
            List[Dict[str, Any]]: Results of the workflow execution.

        Raises:
            InvalidParameterError: If neither workflow identifiers nor specification is provided.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        return self._run_workflow(
            workspace_name=workspace_name,
            workflow_id=workflow_id,
            specification=specification,
            images=images,
            parameters=parameters,
            excluded_fields=excluded_fields,
            legacy_endpoints=False,
            use_cache=use_cache,
            enable_profiling=enable_profiling,
        )

    def _run_workflow(
        self,
        workspace_name: Optional[str] = None,
        workflow_id: Optional[str] = None,
        specification: Optional[dict] = None,
        images: Optional[Dict[str, Any]] = None,
        parameters: Optional[Dict[str, Any]] = None,
        excluded_fields: Optional[List[str]] = None,
        legacy_endpoints: bool = False,
        use_cache: bool = True,
        enable_profiling: bool = False,
    ) -> List[Dict[str, Any]]:
        named_workflow_specified = (workspace_name is not None) and (
            workflow_id is not None
        )
        if not (named_workflow_specified != (specification is not None)):
            raise InvalidParameterError(
                "Parameters (`workspace_name`, `workflow_id` / `workflow_name`) can be used mutually exclusive with "
                "`specification`, but at least one must be set."
            )
        if images is None:
            images = {}
        if parameters is None:
            parameters = {}
        payload = {
            "api_key": self.__api_key,
            "use_cache": use_cache,
            "enable_profiling": enable_profiling,
        }
        inputs = {}
        for image_name, image in images.items():
            loaded_image = load_nested_batches_of_inference_input(
                inference_input=image,
            )
            inject_nested_batches_of_images_into_payload(
                payload=inputs,
                encoded_images=loaded_image,
                key=image_name,
            )
        inputs.update(parameters)
        payload["inputs"] = inputs
        if excluded_fields is not None:
            payload["excluded_fields"] = excluded_fields
        if specification is not None:
            payload["specification"] = specification
        if specification is not None:
            if legacy_endpoints:
                url = f"{self.__api_url}/infer/workflows"
            else:
                url = f"{self.__api_url}/workflows/run"
        else:
            if legacy_endpoints:
                url = f"{self.__api_url}/infer/workflows/{workspace_name}/{workflow_id}"
            else:
                url = f"{self.__api_url}/{workspace_name}/workflows/{workflow_id}"
        response = requests.post(
            url,
            json=payload,
            headers=DEFAULT_HEADERS,
        )
        api_key_safe_raise_for_status(response=response)
        response_data = response.json()
        workflow_outputs = response_data["outputs"]
        profiler_trace = response_data.get("profiler_trace", [])
        if enable_profiling:
            save_workflows_profiler_trace(
                directory=self.__inference_configuration.profiling_directory,
                profiler_trace=profiler_trace,
            )
        return decode_workflow_outputs(
            workflow_outputs=workflow_outputs,
            expected_format=self.__inference_configuration.output_visualisation_format,
        )

    @wrap_errors
    def infer_from_yolo_world(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        class_names: List[str],
        model_version: Optional[str] = None,
        confidence: Optional[float] = None,
    ) -> List[dict]:
        """Run inference using YOLO-World model.

        Args:
            inference_input: Input image(s) to run inference on. Can be a single image
                reference or a list of image references.
            class_names: List of class names to detect in the image(s).
            model_version: Optional version of YOLO-World model to use. If not specified,
                uses the default version.
            confidence: Optional confidence threshold for detections. If not specified,
                uses the model's default threshold.

        Returns:
            List of dictionaries containing detection results for each input image.
            Each dictionary contains bounding boxes, class labels, and confidence scores
            for detected objects.

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        encoded_inference_inputs = load_static_inference_input(
            inference_input=inference_input,
        )
        payload = self.__initialise_payload()
        payload["text"] = class_names
        if model_version is not None:
            payload["yolo_world_version_id"] = model_version
        if confidence is not None:
            payload["confidence"] = confidence
        url = self.__wrap_url_with_api_key(f"{self.__api_url}/yolo_world/infer")
        requests_data = prepare_requests_data(
            url=url,
            encoded_inference_inputs=encoded_inference_inputs,
            headers=DEFAULT_HEADERS,
            parameters=None,
            payload=payload,
            max_batch_size=1,
            image_placement=ImagePlacement.JSON,
        )
        responses = execute_requests_packages(
            requests_data=requests_data,
            request_method=RequestMethod.POST,
            max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
        )
        return [r.json() for r in responses]

    @wrap_errors_async
    async def infer_from_yolo_world_async(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        class_names: List[str],
        model_version: Optional[str] = None,
        confidence: Optional[float] = None,
    ) -> List[dict]:
        """Run inference using YOLO-World model asynchronously.

        Args:
            inference_input: Input image(s) to run inference on. Can be a single image
                reference or a list of image references.
            class_names: List of class names to detect in the image(s).
            model_version: Optional version of YOLO-World model to use. If not specified,
                uses the default version.
            confidence: Optional confidence threshold for detections. If not specified,
                uses the model's default threshold.

        Returns:
            List of dictionaries containing detection results for each input image.
            Each dictionary contains bounding boxes, class labels, and confidence scores
            for detected objects.

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        encoded_inference_inputs = await load_static_inference_input_async(
            inference_input=inference_input,
        )
        payload = self.__initialise_payload()
        payload["text"] = class_names
        if model_version is not None:
            payload["yolo_world_version_id"] = model_version
        if confidence is not None:
            payload["confidence"] = confidence
        url = self.__wrap_url_with_api_key(f"{self.__api_url}/yolo_world/infer")
        requests_data = prepare_requests_data(
            url=url,
            encoded_inference_inputs=encoded_inference_inputs,
            headers=DEFAULT_HEADERS,
            parameters=None,
            payload=payload,
            max_batch_size=1,
            image_placement=ImagePlacement.JSON,
        )
        return await execute_requests_packages_async(
            requests_data=requests_data,
            request_method=RequestMethod.POST,
            max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
        )

    @experimental(
        info="Video processing in inference server is under development. Breaking changes are possible."
    )
    @wrap_errors
    def start_inference_pipeline_with_workflow(
        self,
        video_reference: Union[str, int, List[Union[str, int]]],
        workflow_specification: Optional[dict] = None,
        workspace_name: Optional[str] = None,
        workflow_id: Optional[str] = None,
        image_input_name: str = "image",
        workflows_parameters: Optional[Dict[str, Any]] = None,
        workflows_thread_pool_workers: int = 4,
        cancel_thread_pool_tasks_on_exit: bool = True,
        video_metadata_input_name: str = "video_metadata",
        max_fps: Optional[Union[float, int]] = None,
        source_buffer_filling_strategy: Optional[BufferFillingStrategy] = "DROP_OLDEST",
        source_buffer_consumption_strategy: Optional[
            BufferConsumptionStrategy
        ] = "EAGER",
        video_source_properties: Optional[Dict[str, float]] = None,
        batch_collection_timeout: Optional[float] = None,
        results_buffer_size: int = 64,
    ) -> dict:
        """Starts an inference pipeline using a workflow specification.

        Args:
            video_reference: Path to video file, camera index, or list of video sources.
                Can be a string path, integer camera index, or list of either.
            workflow_specification: Optional workflow specification dictionary. Mutually
                exclusive with workspace_name/workflow_id.
            workspace_name: Optional name of workspace containing workflow. Must be used
                with workflow_id.
            workflow_id: Optional ID of workflow to use. Must be used with workspace_name.
            image_input_name: Name of the image input node in workflow. Defaults to "image".
            workflows_parameters: Optional parameters to pass to workflow.
            workflows_thread_pool_workers: Number of worker threads for workflow execution.
                Defaults to 4.
            cancel_thread_pool_tasks_on_exit: Whether to cancel pending tasks when exiting.
                Defaults to True.
            video_metadata_input_name: Name of video metadata input in workflow.
                Defaults to "video_metadata".
            max_fps: Optional maximum FPS to process video at.
            source_buffer_filling_strategy: Strategy for filling source buffer when full.
                One of: "WAIT", "DROP_OLDEST", "ADAPTIVE_DROP_OLDEST", "DROP_LATEST",
                "ADAPTIVE_DROP_LATEST". Defaults to "DROP_OLDEST".
            source_buffer_consumption_strategy: Strategy for consuming from source buffer.
                One of: "LAZY", "EAGER". Defaults to "EAGER".
            video_source_properties: Optional dictionary of video source properties.
            batch_collection_timeout: Optional timeout for batch collection in seconds.
            results_buffer_size: Size of results buffer. Defaults to 64.

        Returns:
            dict: Response containing pipeline initialization details.

        Raises:
            InvalidParameterError: If workflow specification parameters are invalid.
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        named_workflow_specified = (workspace_name is not None) and (
            workflow_id is not None
        )
        if not (named_workflow_specified != (workflow_specification is not None)):
            raise InvalidParameterError(
                "Parameters (`workspace_name`, `workflow_id`) can be used mutually exclusive with "
                "`workflow_specification`, but at least one must be set."
            )
        payload = {
            "api_key": self.__api_key,
            "video_configuration": {
                "type": "VideoConfiguration",
                "video_reference": video_reference,
                "max_fps": max_fps,
                "source_buffer_filling_strategy": source_buffer_filling_strategy,
                "source_buffer_consumption_strategy": source_buffer_consumption_strategy,
                "video_source_properties": video_source_properties,
                "batch_collection_timeout": batch_collection_timeout,
            },
            "processing_configuration": {
                "type": "WorkflowConfiguration",
                "workflow_specification": workflow_specification,
                "workspace_name": workspace_name,
                "workflow_id": workflow_id,
                "image_input_name": image_input_name,
                "workflows_parameters": workflows_parameters,
                "workflows_thread_pool_workers": workflows_thread_pool_workers,
                "cancel_thread_pool_tasks_on_exit": cancel_thread_pool_tasks_on_exit,
                "video_metadata_input_name": video_metadata_input_name,
            },
            "sink_configuration": {
                "type": "MemorySinkConfiguration",
                "results_buffer_size": results_buffer_size,
            },
        }
        response = requests.post(
            f"{self.__api_url}/inference_pipelines/initialise",
            json=payload,
        )
        response.raise_for_status()
        return response.json()

    @experimental(
        info="Video processing in inference server is under development. Breaking changes are possible."
    )
    @wrap_errors
    def list_inference_pipelines(self) -> List[dict]:
        """Lists all active inference pipelines on the server.

        This method retrieves information about all currently running inference pipelines
        on the server, including their IDs and status.

        Returns:
            List[dict]: A list of dictionaries containing information about each active
                inference pipeline.

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
        """
        payload = {"api_key": self.__api_key}
        response = requests.get(
            f"{self.__api_url}/inference_pipelines/list",
            json=payload,
        )
        api_key_safe_raise_for_status(response=response)
        return response.json()

    @experimental(
        info="Video processing in inference server is under development. Breaking changes are possible."
    )
    @wrap_errors
    def get_inference_pipeline_status(self, pipeline_id: str) -> dict:
        """Gets the current status of a specific inference pipeline.

        Args:
            pipeline_id: The unique identifier of the inference pipeline to check.

        Returns:
            dict: A dictionary containing the current status and details of the pipeline.

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
            ValueError: If pipeline_id is empty or None.
        """
        self._ensure_pipeline_id_not_empty(pipeline_id=pipeline_id)
        payload = {"api_key": self.__api_key}
        response = requests.get(
            f"{self.__api_url}/inference_pipelines/{pipeline_id}/status",
            json=payload,
        )
        api_key_safe_raise_for_status(response=response)
        return response.json()

    @experimental(
        info="Video processing in inference server is under development. Breaking changes are possible."
    )
    @wrap_errors
    def pause_inference_pipeline(self, pipeline_id: str) -> dict:
        """Pauses a running inference pipeline.

        Sends a request to pause the specified inference pipeline. The pipeline must be
        currently running for this operation to succeed.

        Args:
            pipeline_id: The unique identifier of the inference pipeline to pause.

        Returns:
            dict: A dictionary containing the response from the server about the pause operation.

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
            ValueError: If pipeline_id is empty or None.
        """
        self._ensure_pipeline_id_not_empty(pipeline_id=pipeline_id)
        payload = {"api_key": self.__api_key}
        response = requests.post(
            f"{self.__api_url}/inference_pipelines/{pipeline_id}/pause",
            json=payload,
        )
        api_key_safe_raise_for_status(response=response)
        return response.json()

    @experimental(
        info="Video processing in inference server is under development. Breaking changes are possible."
    )
    @wrap_errors
    def resume_inference_pipeline(self, pipeline_id: str) -> dict:
        """Resumes a paused inference pipeline.

        Sends a request to resume the specified inference pipeline. The pipeline must be
        currently paused for this operation to succeed.

        Args:
            pipeline_id: The unique identifier of the inference pipeline to resume.

        Returns:
            dict: A dictionary containing the response from the server about the resume operation.

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
            ValueError: If pipeline_id is empty or None.
        """
        self._ensure_pipeline_id_not_empty(pipeline_id=pipeline_id)
        payload = {"api_key": self.__api_key}
        response = requests.post(
            f"{self.__api_url}/inference_pipelines/{pipeline_id}/resume",
            json=payload,
        )
        api_key_safe_raise_for_status(response=response)
        return response.json()

    @experimental(
        info="Video processing in inference server is under development. Breaking changes are possible."
    )
    @wrap_errors
    def terminate_inference_pipeline(self, pipeline_id: str) -> dict:
        """Terminates a running inference pipeline.

        Sends a request to terminate the specified inference pipeline. This will stop all
        processing and free up associated resources.

        Args:
            pipeline_id: The unique identifier of the inference pipeline to terminate.

        Returns:
            dict: A dictionary containing the response from the server about the termination operation.

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
            ValueError: If pipeline_id is empty or None.
        """
        self._ensure_pipeline_id_not_empty(pipeline_id=pipeline_id)
        payload = {"api_key": self.__api_key}
        response = requests.post(
            f"{self.__api_url}/inference_pipelines/{pipeline_id}/terminate",
            json=payload,
        )
        api_key_safe_raise_for_status(response=response)
        return response.json()

    @experimental(
        info="Video processing in inference server is under development. Breaking changes are possible."
    )
    @wrap_errors
    def consume_inference_pipeline_result(
        self,
        pipeline_id: str,
        excluded_fields: Optional[List[str]] = None,
    ) -> dict:
        """Consumes and returns the next available result from an inference pipeline.

        Args:
            pipeline_id: The unique identifier of the inference pipeline to consume results from.
            excluded_fields: Optional list of field names to exclude from the result. If None,
                no fields will be excluded.

        Returns:
            dict: A dictionary containing the next available result from the pipeline.

        Raises:
            HTTPCallErrorError: If there is an error in the HTTP call.
            HTTPClientError: If there is an error with the server connection.
            InvalidParameterError: If pipeline_id is empty or None.
        """
        self._ensure_pipeline_id_not_empty(pipeline_id=pipeline_id)
        if excluded_fields is None:
            excluded_fields = []
        payload = {"api_key": self.__api_key, "excluded_fields": excluded_fields}
        response = requests.get(
            f"{self.__api_url}/inference_pipelines/{pipeline_id}/consume",
            json=payload,
        )
        api_key_safe_raise_for_status(response=response)
        return response.json()

    def _ensure_pipeline_id_not_empty(self, pipeline_id: str) -> None:
        if not pipeline_id:
            raise InvalidParameterError("Empty `pipeline_id` parameter detected")

    def _post_images(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        endpoint: str,
        model_id: Optional[str] = None,
        extra_payload: Optional[Dict[str, Any]] = None,
    ) -> Union[dict, List[dict]]:
        encoded_inference_inputs = load_static_inference_input(
            inference_input=inference_input,
        )
        payload = self.__initialise_payload()
        if model_id is not None:
            payload["model_id"] = model_id
        url = self.__wrap_url_with_api_key(f"{self.__api_url}{endpoint}")
        if extra_payload is not None:
            payload.update(extra_payload)
        requests_data = prepare_requests_data(
            url=url,
            encoded_inference_inputs=encoded_inference_inputs,
            headers=DEFAULT_HEADERS,
            parameters=None,
            payload=payload,
            max_batch_size=self.__inference_configuration.max_batch_size,
            image_placement=ImagePlacement.JSON,
        )
        responses = execute_requests_packages(
            requests_data=requests_data,
            request_method=RequestMethod.POST,
            max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
        )
        results = [r.json() for r in responses]
        return unwrap_single_element_list(sequence=results)

    async def _post_images_async(
        self,
        inference_input: Union[ImagesReference, List[ImagesReference]],
        endpoint: str,
        model_id: Optional[str] = None,
        extra_payload: Optional[Dict[str, Any]] = None,
    ) -> Union[dict, List[dict]]:
        encoded_inference_inputs = await load_static_inference_input_async(
            inference_input=inference_input,
        )
        payload = self.__initialise_payload()
        if model_id is not None:
            payload["model_id"] = model_id
        url = self.__wrap_url_with_api_key(f"{self.__api_url}{endpoint}")
        if extra_payload is not None:
            payload.update(extra_payload)
        requests_data = prepare_requests_data(
            url=url,
            encoded_inference_inputs=encoded_inference_inputs,
            headers=DEFAULT_HEADERS,
            parameters=None,
            payload=payload,
            max_batch_size=self.__inference_configuration.max_batch_size,
            image_placement=ImagePlacement.JSON,
        )
        responses = await execute_requests_packages_async(
            requests_data=requests_data,
            request_method=RequestMethod.POST,
            max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
        )
        return unwrap_single_element_list(sequence=responses)

    def __initialise_payload(self) -> dict:
        if self.__client_mode is not HTTPClientMode.V0:
            return {"api_key": self.__api_key}
        return {}

    def __wrap_url_with_api_key(self, url: str) -> str:
        if self.__client_mode is not HTTPClientMode.V0:
            return url
        return f"{url}?api_key={self.__api_key}"

    def __ensure_v1_client_mode(self) -> None:
        if self.__client_mode is not HTTPClientMode.V1:
            raise WrongClientModeError("Use client mode `v1` to run this operation.")

client_mode property

Get the current client mode.

Returns:

Name Type Description
HTTPClientMode HTTPClientMode

The current API version mode (V0 or V1).

inference_configuration property

Get the current inference configuration.

Returns:

Name Type Description
InferenceConfiguration InferenceConfiguration

The current inference configuration settings.

selected_model property

Get the currently selected model identifier.

Returns:

Type Description
Optional[str]

Optional[str]: The identifier of the currently selected model, if any.

__init__(api_url, api_key=None)

Initialize a new InferenceHTTPClient instance.

Parameters:

Name Type Description Default
api_url str

The base URL for the inference API.

required
api_key Optional[str]

API key for authentication. Defaults to None.

None
Source code in inference_sdk/http/client.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def __init__(
    self,
    api_url: str,
    api_key: Optional[str] = None,
):
    """Initialize a new InferenceHTTPClient instance.

    Args:
        api_url (str): The base URL for the inference API.
        api_key (Optional[str], optional): API key for authentication. Defaults to None.
    """
    self.__api_url = api_url
    self.__api_key = api_key
    self.__inference_configuration = InferenceConfiguration.init_default()
    self.__client_mode = _determine_client_mode(api_url=api_url)
    self.__selected_model: Optional[str] = None

clip_compare(subject, prompt, subject_type='image', prompt_type='text', clip_version=None)

Compare a subject against prompts using CLIP embeddings.

Parameters:

Name Type Description Default
subject Union[str, ImagesReference]

The subject to compare (image or text).

required
prompt Union[str, List[str], ImagesReference, List[ImagesReference]]

The prompt(s) to compare against.

required
subject_type str

Type of subject ('image' or 'text'). Defaults to "image".

'image'
prompt_type str

Type of prompt(s) ('image' or 'text'). Defaults to "text".

'text'
clip_version Optional[str]

Version of CLIP model to use. Defaults to None.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: Comparison results between subject and prompt(s).

Raises:

Type Description
InvalidParameterError

If subject_type or prompt_type is invalid.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors
def clip_compare(
    self,
    subject: Union[str, ImagesReference],
    prompt: Union[str, List[str], ImagesReference, List[ImagesReference]],
    subject_type: str = "image",
    prompt_type: str = "text",
    clip_version: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Compare a subject against prompts using CLIP embeddings.

    Args:
        subject (Union[str, ImagesReference]): The subject to compare (image or text).
        prompt (Union[str, List[str], ImagesReference, List[ImagesReference]]): The prompt(s) to compare against.
        subject_type (str, optional): Type of subject ('image' or 'text'). Defaults to "image".
        prompt_type (str, optional): Type of prompt(s) ('image' or 'text'). Defaults to "text".
        clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

    Returns:
        Union[dict, List[dict]]: Comparison results between subject and prompt(s).

    Raises:
        InvalidParameterError: If subject_type or prompt_type is invalid.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    if (
        subject_type not in CLIP_ARGUMENT_TYPES
        or prompt_type not in CLIP_ARGUMENT_TYPES
    ):
        raise InvalidParameterError(
            f"Could not accept `subject_type` and `prompt_type` with values different than {CLIP_ARGUMENT_TYPES}"
        )
    payload = self.__initialise_payload()
    payload["subject_type"] = subject_type
    payload["prompt_type"] = prompt_type
    if clip_version is not None:
        payload["clip_version_id"] = clip_version
    if subject_type == "image":
        encoded_image = load_static_inference_input(
            inference_input=subject,
        )
        payload = inject_images_into_payload(
            payload=payload, encoded_images=encoded_image, key="subject"
        )
    else:
        payload["subject"] = subject
    if prompt_type == "image":
        encoded_inference_inputs = load_static_inference_input(
            inference_input=prompt,
        )
        payload = inject_images_into_payload(
            payload=payload, encoded_images=encoded_inference_inputs, key="prompt"
        )
    else:
        payload["prompt"] = prompt
    response = requests.post(
        self.__wrap_url_with_api_key(f"{self.__api_url}/clip/compare"),
        json=payload,
        headers=DEFAULT_HEADERS,
    )
    api_key_safe_raise_for_status(response=response)
    return response.json()

clip_compare_async(subject, prompt, subject_type='image', prompt_type='text', clip_version=None) async

Compare a subject against prompts using CLIP embeddings asynchronously.

Parameters:

Name Type Description Default
subject Union[str, ImagesReference]

The subject to compare (image or text).

required
prompt Union[str, List[str], ImagesReference, List[ImagesReference]]

The prompt(s) to compare against.

required
subject_type str

Type of subject ('image' or 'text'). Defaults to "image".

'image'
prompt_type str

Type of prompt(s) ('image' or 'text'). Defaults to "text".

'text'
clip_version Optional[str]

Version of CLIP model to use. Defaults to None.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: Comparison results between subject and prompt(s).

Raises:

Type Description
InvalidParameterError

If subject_type or prompt_type is invalid.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors_async
async def clip_compare_async(
    self,
    subject: Union[str, ImagesReference],
    prompt: Union[str, List[str], ImagesReference, List[ImagesReference]],
    subject_type: str = "image",
    prompt_type: str = "text",
    clip_version: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Compare a subject against prompts using CLIP embeddings asynchronously.

    Args:
        subject (Union[str, ImagesReference]): The subject to compare (image or text).
        prompt (Union[str, List[str], ImagesReference, List[ImagesReference]]): The prompt(s) to compare against.
        subject_type (str, optional): Type of subject ('image' or 'text'). Defaults to "image".
        prompt_type (str, optional): Type of prompt(s) ('image' or 'text'). Defaults to "text".
        clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

    Returns:
        Union[dict, List[dict]]: Comparison results between subject and prompt(s).

    Raises:
        InvalidParameterError: If subject_type or prompt_type is invalid.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    if (
        subject_type not in CLIP_ARGUMENT_TYPES
        or prompt_type not in CLIP_ARGUMENT_TYPES
    ):
        raise InvalidParameterError(
            f"Could not accept `subject_type` and `prompt_type` with values different than {CLIP_ARGUMENT_TYPES}"
        )
    payload = self.__initialise_payload()
    payload["subject_type"] = subject_type
    payload["prompt_type"] = prompt_type
    if clip_version is not None:
        payload["clip_version_id"] = clip_version
    if subject_type == "image":
        encoded_image = await load_static_inference_input_async(
            inference_input=subject,
        )
        payload = inject_images_into_payload(
            payload=payload, encoded_images=encoded_image, key="subject"
        )
    else:
        payload["subject"] = subject
    if prompt_type == "image":
        encoded_inference_inputs = await load_static_inference_input_async(
            inference_input=prompt,
        )
        payload = inject_images_into_payload(
            payload=payload, encoded_images=encoded_inference_inputs, key="prompt"
        )
    else:
        payload["prompt"] = prompt

    async with aiohttp.ClientSession() as session:
        async with session.post(
            self.__wrap_url_with_api_key(f"{self.__api_url}/clip/compare"),
            json=payload,
            headers=DEFAULT_HEADERS,
        ) as response:
            response.raise_for_status()
            return await response.json()

configure(inference_configuration)

Configure the client with new inference settings.

Parameters:

Name Type Description Default
inference_configuration InferenceConfiguration

The new configuration to apply.

required

Returns:

Name Type Description
InferenceHTTPClient InferenceHTTPClient

The client instance with updated configuration.

Source code in inference_sdk/http/client.py
251
252
253
254
255
256
257
258
259
260
261
262
263
def configure(
    self, inference_configuration: InferenceConfiguration
) -> "InferenceHTTPClient":
    """Configure the client with new inference settings.

    Args:
        inference_configuration (InferenceConfiguration): The new configuration to apply.

    Returns:
        InferenceHTTPClient: The client instance with updated configuration.
    """
    self.__inference_configuration = inference_configuration
    return self

consume_inference_pipeline_result(pipeline_id, excluded_fields=None)

Consumes and returns the next available result from an inference pipeline.

Parameters:

Name Type Description Default
pipeline_id str

The unique identifier of the inference pipeline to consume results from.

required
excluded_fields Optional[List[str]]

Optional list of field names to exclude from the result. If None, no fields will be excluded.

None

Returns:

Name Type Description
dict dict

A dictionary containing the next available result from the pipeline.

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

InvalidParameterError

If pipeline_id is empty or None.

Source code in inference_sdk/http/client.py
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
@experimental(
    info="Video processing in inference server is under development. Breaking changes are possible."
)
@wrap_errors
def consume_inference_pipeline_result(
    self,
    pipeline_id: str,
    excluded_fields: Optional[List[str]] = None,
) -> dict:
    """Consumes and returns the next available result from an inference pipeline.

    Args:
        pipeline_id: The unique identifier of the inference pipeline to consume results from.
        excluded_fields: Optional list of field names to exclude from the result. If None,
            no fields will be excluded.

    Returns:
        dict: A dictionary containing the next available result from the pipeline.

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
        InvalidParameterError: If pipeline_id is empty or None.
    """
    self._ensure_pipeline_id_not_empty(pipeline_id=pipeline_id)
    if excluded_fields is None:
        excluded_fields = []
    payload = {"api_key": self.__api_key, "excluded_fields": excluded_fields}
    response = requests.get(
        f"{self.__api_url}/inference_pipelines/{pipeline_id}/consume",
        json=payload,
    )
    api_key_safe_raise_for_status(response=response)
    return response.json()

detect_gazes(inference_input)

Detect gazes in input image(s).

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) for gaze detection.

required

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: Gaze detection results for the input image(s).

Raises:

Type Description
WrongClientModeError

If not in API v1 mode.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
@wrap_errors
def detect_gazes(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
) -> Union[dict, List[dict]]:
    """Detect gazes in input image(s).

    Args:
        inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for gaze detection.

    Returns:
        Union[dict, List[dict]]: Gaze detection results for the input image(s).

    Raises:
        WrongClientModeError: If not in API v1 mode.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    self.__ensure_v1_client_mode()  # Lambda does not support Gaze, so we require v1 mode of client
    result = self._post_images(
        inference_input=inference_input, endpoint="/gaze/gaze_detection"
    )
    return combine_gaze_detections(detections=result)

detect_gazes_async(inference_input) async

Detect gazes in input image(s) asynchronously.

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) for gaze detection.

required

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: Gaze detection results for the input image(s).

Raises:

Type Description
WrongClientModeError

If not in API v1 mode.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
@wrap_errors_async
async def detect_gazes_async(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
) -> Union[dict, List[dict]]:
    """Detect gazes in input image(s) asynchronously.

    Args:
        inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for gaze detection.

    Returns:
        Union[dict, List[dict]]: Gaze detection results for the input image(s).

    Raises:
        WrongClientModeError: If not in API v1 mode.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    self.__ensure_v1_client_mode()  # Lambda does not support Gaze, so we require v1 mode of client
    result = await self._post_images_async(
        inference_input=inference_input, endpoint="/gaze/gaze_detection"
    )
    return combine_gaze_detections(detections=result)

get_clip_image_embeddings(inference_input, clip_version=None)

Get CLIP embeddings for input image(s).

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) to embed.

required
clip_version Optional[str]

Version of CLIP model to use. Defaults to None.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: CLIP embeddings for the input image(s).

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors
def get_clip_image_embeddings(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
    clip_version: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Get CLIP embeddings for input image(s).

    Args:
        inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) to embed.
        clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

    Returns:
        Union[dict, List[dict]]: CLIP embeddings for the input image(s).

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    extra_payload = {}
    if clip_version is not None:
        extra_payload["clip_version_id"] = clip_version
    result = self._post_images(
        inference_input=inference_input,
        endpoint="/clip/embed_image",
        extra_payload=extra_payload,
    )
    result = combine_clip_embeddings(embeddings=result)
    return unwrap_single_element_list(result)

get_clip_image_embeddings_async(inference_input, clip_version=None) async

Get CLIP embeddings for input image(s) asynchronously.

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) to embed.

required
clip_version Optional[str]

Version of CLIP model to use. Defaults to None.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: CLIP embeddings for the input image(s).

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors_async
async def get_clip_image_embeddings_async(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
    clip_version: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Get CLIP embeddings for input image(s) asynchronously.

    Args:
        inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) to embed.
        clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

    Returns:
        Union[dict, List[dict]]: CLIP embeddings for the input image(s).

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    extra_payload = {}
    if clip_version is not None:
        extra_payload["clip_version_id"] = clip_version
    result = await self._post_images_async(
        inference_input=inference_input,
        endpoint="/clip/embed_image",
        extra_payload=extra_payload,
    )
    result = combine_clip_embeddings(embeddings=result)
    return unwrap_single_element_list(result)

get_clip_text_embeddings(text, clip_version=None)

Get CLIP embeddings for input text(s).

Parameters:

Name Type Description Default
text Union[str, List[str]]

Input text(s) to embed.

required
clip_version Optional[str]

Version of CLIP model to use. Defaults to None.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: CLIP embeddings for the input text(s).

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors
def get_clip_text_embeddings(
    self,
    text: Union[str, List[str]],
    clip_version: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Get CLIP embeddings for input text(s).

    Args:
        text (Union[str, List[str]]): Input text(s) to embed.
        clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

    Returns:
        Union[dict, List[dict]]: CLIP embeddings for the input text(s).

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    payload = self.__initialise_payload()
    payload["text"] = text
    if clip_version is not None:
        payload["clip_version_id"] = clip_version
    response = requests.post(
        self.__wrap_url_with_api_key(f"{self.__api_url}/clip/embed_text"),
        json=payload,
        headers=DEFAULT_HEADERS,
    )
    api_key_safe_raise_for_status(response=response)
    return unwrap_single_element_list(sequence=response.json())

get_clip_text_embeddings_async(text, clip_version=None) async

Get CLIP embeddings for input text(s) asynchronously.

Parameters:

Name Type Description Default
text Union[str, List[str]]

Input text(s) to embed.

required
clip_version Optional[str]

Version of CLIP model to use. Defaults to None.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: CLIP embeddings for the input text(s).

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors_async
async def get_clip_text_embeddings_async(
    self,
    text: Union[str, List[str]],
    clip_version: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Get CLIP embeddings for input text(s) asynchronously.

    Args:
        text (Union[str, List[str]]): Input text(s) to embed.
        clip_version (Optional[str], optional): Version of CLIP model to use. Defaults to None.

    Returns:
        Union[dict, List[dict]]: CLIP embeddings for the input text(s).

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    payload = self.__initialise_payload()
    payload["text"] = text
    if clip_version is not None:
        payload["clip_version_id"] = clip_version
    async with aiohttp.ClientSession() as session:
        async with session.post(
            self.__wrap_url_with_api_key(f"{self.__api_url}/clip/embed_text"),
            json=payload,
            headers=DEFAULT_HEADERS,
        ) as response:
            response.raise_for_status()
            response_payload = await response.json()
    return unwrap_single_element_list(sequence=response_payload)

get_inference_pipeline_status(pipeline_id)

Gets the current status of a specific inference pipeline.

Parameters:

Name Type Description Default
pipeline_id str

The unique identifier of the inference pipeline to check.

required

Returns:

Name Type Description
dict dict

A dictionary containing the current status and details of the pipeline.

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

ValueError

If pipeline_id is empty or None.

Source code in inference_sdk/http/client.py
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
@experimental(
    info="Video processing in inference server is under development. Breaking changes are possible."
)
@wrap_errors
def get_inference_pipeline_status(self, pipeline_id: str) -> dict:
    """Gets the current status of a specific inference pipeline.

    Args:
        pipeline_id: The unique identifier of the inference pipeline to check.

    Returns:
        dict: A dictionary containing the current status and details of the pipeline.

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
        ValueError: If pipeline_id is empty or None.
    """
    self._ensure_pipeline_id_not_empty(pipeline_id=pipeline_id)
    payload = {"api_key": self.__api_key}
    response = requests.get(
        f"{self.__api_url}/inference_pipelines/{pipeline_id}/status",
        json=payload,
    )
    api_key_safe_raise_for_status(response=response)
    return response.json()

get_model_description(model_id, allow_loading=True)

Get the description of a model.

Parameters:

Name Type Description Default
model_id str

The identifier of the model.

required
allow_loading bool

Whether to load the model if not already loaded. Defaults to True.

True

Returns:

Name Type Description
ModelDescription ModelDescription

Description of the model.

Raises:

Type Description
WrongClientModeError

If not in API v1 mode.

ModelNotInitializedError

If the model is not initialized and cannot be loaded.

Source code in inference_sdk/http/client.py
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
def get_model_description(
    self, model_id: str, allow_loading: bool = True
) -> ModelDescription:
    """Get the description of a model.

    Args:
        model_id (str): The identifier of the model.
        allow_loading (bool, optional): Whether to load the model if not already loaded. Defaults to True.

    Returns:
        ModelDescription: Description of the model.

    Raises:
        WrongClientModeError: If not in API v1 mode.
        ModelNotInitializedError: If the model is not initialized and cannot be loaded.
    """
    self.__ensure_v1_client_mode()
    de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
    registered_models = self.list_loaded_models()
    matching_model = filter_model_descriptions(
        descriptions=registered_models.models,
        model_id=de_aliased_model_id,
    )
    if matching_model is None and allow_loading is True:
        registered_models = self.load_model(model_id=de_aliased_model_id)
        matching_model = filter_model_descriptions(
            descriptions=registered_models.models,
            model_id=de_aliased_model_id,
        )
    if matching_model is not None:
        return matching_model
    raise ModelNotInitializedError(
        f"Model {model_id} (de-aliased: {de_aliased_model_id}) is not initialised and cannot "
        f"retrieve its description."
    )

get_model_description_async(model_id, allow_loading=True) async

Get the description of a model asynchronously.

Parameters:

Name Type Description Default
model_id str

The identifier of the model.

required
allow_loading bool

Whether to load the model if not already loaded. Defaults to True.

True

Returns:

Name Type Description
ModelDescription ModelDescription

Description of the model.

Raises:

Type Description
WrongClientModeError

If not in API v1 mode.

ModelNotInitializedError

If the model is not initialized and cannot be loaded.

Source code in inference_sdk/http/client.py
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
async def get_model_description_async(
    self, model_id: str, allow_loading: bool = True
) -> ModelDescription:
    """Get the description of a model asynchronously.

    Args:
        model_id (str): The identifier of the model.
        allow_loading (bool, optional): Whether to load the model if not already loaded. Defaults to True.

    Returns:
        ModelDescription: Description of the model.

    Raises:
        WrongClientModeError: If not in API v1 mode.
        ModelNotInitializedError: If the model is not initialized and cannot be loaded.
    """
    self.__ensure_v1_client_mode()
    de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
    registered_models = await self.list_loaded_models_async()
    matching_model = filter_model_descriptions(
        descriptions=registered_models.models,
        model_id=de_aliased_model_id,
    )
    if matching_model is None and allow_loading is True:
        registered_models = await self.load_model_async(
            model_id=de_aliased_model_id
        )
        matching_model = filter_model_descriptions(
            descriptions=registered_models.models,
            model_id=de_aliased_model_id,
        )
    if matching_model is not None:
        return matching_model
    raise ModelNotInitializedError(
        f"Model {model_id} (de-aliased: {de_aliased_model_id}) is not initialised and cannot "
        f"retrieve its description."
    )

get_server_info()

Get information about the inference server.

Returns:

Name Type Description
ServerInfo ServerInfo

Information about the server configuration and status.

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
@wrap_errors
def get_server_info(self) -> ServerInfo:
    """Get information about the inference server.

    Returns:
        ServerInfo: Information about the server configuration and status.

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    response = requests.get(f"{self.__api_url}/info")
    response.raise_for_status()
    response_payload = response.json()
    return ServerInfo.from_dict(response_payload)

infer(inference_input, model_id=None)

Run inference on one or more images.

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) for inference.

required
model_id Optional[str]

Model identifier to use for inference. Defaults to None.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: Inference results for the input image(s).

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors
def infer(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
    model_id: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Run inference on one or more images.

    Args:
        inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for inference.
        model_id (Optional[str], optional): Model identifier to use for inference. Defaults to None.

    Returns:
        Union[dict, List[dict]]: Inference results for the input image(s).

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    if self.__client_mode is HTTPClientMode.V0:
        return self.infer_from_api_v0(
            inference_input=inference_input,
            model_id=model_id,
        )
    return self.infer_from_api_v1(
        inference_input=inference_input,
        model_id=model_id,
    )

infer_async(inference_input, model_id=None) async

Run inference asynchronously on one or more images.

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) for inference.

required
model_id Optional[str]

Model identifier to use for inference. Defaults to None.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: Inference results for the input image(s).

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors_async
async def infer_async(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
    model_id: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Run inference asynchronously on one or more images.

    Args:
        inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for inference.
        model_id (Optional[str], optional): Model identifier to use for inference. Defaults to None.

    Returns:
        Union[dict, List[dict]]: Inference results for the input image(s).

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    if self.__client_mode is HTTPClientMode.V0:
        return await self.infer_from_api_v0_async(
            inference_input=inference_input,
            model_id=model_id,
        )
    return await self.infer_from_api_v1_async(
        inference_input=inference_input,
        model_id=model_id,
    )

infer_from_api_v0(inference_input, model_id=None)

Run inference using API v0.

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) for inference.

required
model_id Optional[str]

Model identifier to use for inference. Defaults to None.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: Inference results for the input image(s).

Raises:

Type Description
ModelNotSelectedError

If no model is selected.

APIKeyNotProvided

If API key is required but not provided.

InvalidModelIdentifier

If the model identifier format is invalid.

Source code in inference_sdk/http/client.py
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
def infer_from_api_v0(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
    model_id: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Run inference using API v0.

    Args:
        inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for inference.
        model_id (Optional[str], optional): Model identifier to use for inference. Defaults to None.

    Returns:
        Union[dict, List[dict]]: Inference results for the input image(s).

    Raises:
        ModelNotSelectedError: If no model is selected.
        APIKeyNotProvided: If API key is required but not provided.
        InvalidModelIdentifier: If the model identifier format is invalid.
    """
    model_id_to_be_used = model_id or self.__selected_model
    _ensure_model_is_selected(model_id=model_id_to_be_used)
    _ensure_api_key_provided(api_key=self.__api_key)
    model_id_to_be_used = resolve_roboflow_model_alias(model_id=model_id_to_be_used)
    model_id_chunks = model_id_to_be_used.split("/")
    if len(model_id_chunks) != 2:
        raise InvalidModelIdentifier(
            f"Invalid model id: {model_id}. Expected format: project_id/model_version_id."
        )
    max_height, max_width = _determine_client_downsizing_parameters(
        client_downsizing_disabled=self.__inference_configuration.client_downsizing_disabled,
        model_description=None,
        default_max_input_size=self.__inference_configuration.default_max_input_size,
    )
    encoded_inference_inputs = load_static_inference_input(
        inference_input=inference_input,
        max_height=max_height,
        max_width=max_width,
    )
    params = {
        "api_key": self.__api_key,
    }
    params.update(self.__inference_configuration.to_legacy_call_parameters())
    requests_data = prepare_requests_data(
        url=f"{self.__api_url}/{model_id_chunks[0]}/{model_id_chunks[1]}",
        encoded_inference_inputs=encoded_inference_inputs,
        headers=DEFAULT_HEADERS,
        parameters=params,
        payload=None,
        max_batch_size=1,
        image_placement=ImagePlacement.DATA,
    )
    responses = execute_requests_packages(
        requests_data=requests_data,
        request_method=RequestMethod.POST,
        max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
    )
    results = []
    for request_data, response in zip(requests_data, responses):
        if response_contains_jpeg_image(response=response):
            visualisation = transform_visualisation_bytes(
                visualisation=response.content,
                expected_format=self.__inference_configuration.output_visualisation_format,
            )
            parsed_response = {"visualization": visualisation}
        else:
            parsed_response = response.json()
            if parsed_response.get("visualization") is not None:
                parsed_response["visualization"] = transform_base64_visualisation(
                    visualisation=parsed_response["visualization"],
                    expected_format=self.__inference_configuration.output_visualisation_format,
                )
        parsed_response = adjust_prediction_to_client_scaling_factor(
            prediction=parsed_response,
            scaling_factor=request_data.image_scaling_factors[0],
        )
        results.append(parsed_response)
    return unwrap_single_element_list(sequence=results)

infer_from_api_v0_async(inference_input, model_id=None) async

Run inference using API v0 asynchronously.

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) for inference.

required
model_id Optional[str]

Model identifier to use for inference. Defaults to None.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: Inference results for the input image(s).

Raises:

Type Description
ModelNotSelectedError

If no model is selected.

APIKeyNotProvided

If API key is required but not provided.

InvalidModelIdentifier

If the model identifier format is invalid.

Source code in inference_sdk/http/client.py
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
async def infer_from_api_v0_async(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
    model_id: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Run inference using API v0 asynchronously.

    Args:
        inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for inference.
        model_id (Optional[str], optional): Model identifier to use for inference. Defaults to None.

    Returns:
        Union[dict, List[dict]]: Inference results for the input image(s).

    Raises:
        ModelNotSelectedError: If no model is selected.
        APIKeyNotProvided: If API key is required but not provided.
        InvalidModelIdentifier: If the model identifier format is invalid.
    """
    model_id_to_be_used = model_id or self.__selected_model
    _ensure_model_is_selected(model_id=model_id_to_be_used)
    _ensure_api_key_provided(api_key=self.__api_key)
    model_id_to_be_used = resolve_roboflow_model_alias(model_id=model_id_to_be_used)
    model_id_chunks = model_id_to_be_used.split("/")
    if len(model_id_chunks) != 2:
        raise InvalidModelIdentifier(
            f"Invalid model id: {model_id}. Expected format: project_id/model_version_id."
        )
    max_height, max_width = _determine_client_downsizing_parameters(
        client_downsizing_disabled=self.__inference_configuration.client_downsizing_disabled,
        model_description=None,
        default_max_input_size=self.__inference_configuration.default_max_input_size,
    )
    encoded_inference_inputs = await load_static_inference_input_async(
        inference_input=inference_input,
        max_height=max_height,
        max_width=max_width,
    )
    params = {
        "api_key": self.__api_key,
    }
    params.update(self.__inference_configuration.to_legacy_call_parameters())
    requests_data = prepare_requests_data(
        url=f"{self.__api_url}/{model_id_chunks[0]}/{model_id_chunks[1]}",
        encoded_inference_inputs=encoded_inference_inputs,
        headers=DEFAULT_HEADERS,
        parameters=params,
        payload=None,
        max_batch_size=1,
        image_placement=ImagePlacement.DATA,
    )
    responses = await execute_requests_packages_async(
        requests_data=requests_data,
        request_method=RequestMethod.POST,
        max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
    )
    results = []
    for request_data, response in zip(requests_data, responses):
        if not issubclass(type(response), dict):
            visualisation = transform_visualisation_bytes(
                visualisation=response,
                expected_format=self.__inference_configuration.output_visualisation_format,
            )
            parsed_response = {"visualization": visualisation}
        else:
            parsed_response = response
            if parsed_response.get("visualization") is not None:
                parsed_response["visualization"] = transform_base64_visualisation(
                    visualisation=parsed_response["visualization"],
                    expected_format=self.__inference_configuration.output_visualisation_format,
                )
        parsed_response = adjust_prediction_to_client_scaling_factor(
            prediction=parsed_response,
            scaling_factor=request_data.image_scaling_factors[0],
        )
        results.append(parsed_response)
    return unwrap_single_element_list(sequence=results)

infer_from_workflow(workspace_name=None, workflow_name=None, specification=None, images=None, parameters=None, excluded_fields=None, use_cache=True, enable_profiling=False)

Run inference using a workflow specification.

Triggers inference from workflow specification at the inference HTTP side. Either (workspace_name and workflow_name) or workflow_specification must be provided. In the first case - definition of workflow will be fetched from Roboflow API, in the latter - workflow_specification will be used. images and parameters will be merged into workflow inputs, the distinction is made to make sure the SDK can easily serialise images and prepare a proper payload. Supported images are numpy arrays, PIL.Image and base64 images, links to images and local paths. excluded_fields will be added to request to filter out results of workflow execution at the server side.

Parameters:

Name Type Description Default
workspace_name Optional[str]

Name of the workspace containing the workflow. Defaults to None.

None
workflow_name Optional[str]

Name of the workflow. Defaults to None.

None
specification Optional[dict]

Direct workflow specification. Defaults to None.

None
images Optional[Dict[str, Any]]

Images to process. Defaults to None.

None
parameters Optional[Dict[str, Any]]

Additional parameters for the workflow. Defaults to None.

None
excluded_fields Optional[List[str]]

Fields to exclude from results. Defaults to None.

None
use_cache bool

Whether to use cached results. Defaults to True.

True
enable_profiling bool

Whether to enable profiling. Defaults to False.

False

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Results of the workflow execution.

Raises:

Type Description
InvalidParameterError

If neither workflow identifiers nor specification is provided.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@deprecated(
    reason="Please use run_workflow(...) method. This method will be removed end of Q2 2024"
)
@wrap_errors
def infer_from_workflow(
    self,
    workspace_name: Optional[str] = None,
    workflow_name: Optional[str] = None,
    specification: Optional[dict] = None,
    images: Optional[Dict[str, Any]] = None,
    parameters: Optional[Dict[str, Any]] = None,
    excluded_fields: Optional[List[str]] = None,
    use_cache: bool = True,
    enable_profiling: bool = False,
) -> List[Dict[str, Any]]:
    """Run inference using a workflow specification.

    Triggers inference from workflow specification at the inference HTTP
    side. Either (`workspace_name` and `workflow_name`) or `workflow_specification` must be
    provided. In the first case - definition of workflow will be fetched
    from Roboflow API, in the latter - `workflow_specification` will be
    used. `images` and `parameters` will be merged into workflow inputs,
    the distinction is made to make sure the SDK can easily serialise
    images and prepare a proper payload. Supported images are numpy arrays,
    PIL.Image and base64 images, links to images and local paths.
    `excluded_fields` will be added to request to filter out results
    of workflow execution at the server side.

    Args:
        workspace_name (Optional[str], optional): Name of the workspace containing the workflow. Defaults to None.
        workflow_name (Optional[str], optional): Name of the workflow. Defaults to None.
        specification (Optional[dict], optional): Direct workflow specification. Defaults to None.
        images (Optional[Dict[str, Any]], optional): Images to process. Defaults to None.
        parameters (Optional[Dict[str, Any]], optional): Additional parameters for the workflow. Defaults to None.
        excluded_fields (Optional[List[str]], optional): Fields to exclude from results. Defaults to None.
        use_cache (bool, optional): Whether to use cached results. Defaults to True.
        enable_profiling (bool, optional): Whether to enable profiling. Defaults to False.

    Returns:
        List[Dict[str, Any]]: Results of the workflow execution.

    Raises:
        InvalidParameterError: If neither workflow identifiers nor specification is provided.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    return self._run_workflow(
        workspace_name=workspace_name,
        workflow_id=workflow_name,
        specification=specification,
        images=images,
        parameters=parameters,
        excluded_fields=excluded_fields,
        legacy_endpoints=True,
        use_cache=use_cache,
        enable_profiling=enable_profiling,
    )

infer_from_yolo_world(inference_input, class_names, model_version=None, confidence=None)

Run inference using YOLO-World model.

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) to run inference on. Can be a single image reference or a list of image references.

required
class_names List[str]

List of class names to detect in the image(s).

required
model_version Optional[str]

Optional version of YOLO-World model to use. If not specified, uses the default version.

None
confidence Optional[float]

Optional confidence threshold for detections. If not specified, uses the model's default threshold.

None

Returns:

Type Description
List[dict]

List of dictionaries containing detection results for each input image.

List[dict]

Each dictionary contains bounding boxes, class labels, and confidence scores

List[dict]

for detected objects.

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors
def infer_from_yolo_world(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
    class_names: List[str],
    model_version: Optional[str] = None,
    confidence: Optional[float] = None,
) -> List[dict]:
    """Run inference using YOLO-World model.

    Args:
        inference_input: Input image(s) to run inference on. Can be a single image
            reference or a list of image references.
        class_names: List of class names to detect in the image(s).
        model_version: Optional version of YOLO-World model to use. If not specified,
            uses the default version.
        confidence: Optional confidence threshold for detections. If not specified,
            uses the model's default threshold.

    Returns:
        List of dictionaries containing detection results for each input image.
        Each dictionary contains bounding boxes, class labels, and confidence scores
        for detected objects.

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    encoded_inference_inputs = load_static_inference_input(
        inference_input=inference_input,
    )
    payload = self.__initialise_payload()
    payload["text"] = class_names
    if model_version is not None:
        payload["yolo_world_version_id"] = model_version
    if confidence is not None:
        payload["confidence"] = confidence
    url = self.__wrap_url_with_api_key(f"{self.__api_url}/yolo_world/infer")
    requests_data = prepare_requests_data(
        url=url,
        encoded_inference_inputs=encoded_inference_inputs,
        headers=DEFAULT_HEADERS,
        parameters=None,
        payload=payload,
        max_batch_size=1,
        image_placement=ImagePlacement.JSON,
    )
    responses = execute_requests_packages(
        requests_data=requests_data,
        request_method=RequestMethod.POST,
        max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
    )
    return [r.json() for r in responses]

infer_from_yolo_world_async(inference_input, class_names, model_version=None, confidence=None) async

Run inference using YOLO-World model asynchronously.

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) to run inference on. Can be a single image reference or a list of image references.

required
class_names List[str]

List of class names to detect in the image(s).

required
model_version Optional[str]

Optional version of YOLO-World model to use. If not specified, uses the default version.

None
confidence Optional[float]

Optional confidence threshold for detections. If not specified, uses the model's default threshold.

None

Returns:

Type Description
List[dict]

List of dictionaries containing detection results for each input image.

List[dict]

Each dictionary contains bounding boxes, class labels, and confidence scores

List[dict]

for detected objects.

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors_async
async def infer_from_yolo_world_async(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
    class_names: List[str],
    model_version: Optional[str] = None,
    confidence: Optional[float] = None,
) -> List[dict]:
    """Run inference using YOLO-World model asynchronously.

    Args:
        inference_input: Input image(s) to run inference on. Can be a single image
            reference or a list of image references.
        class_names: List of class names to detect in the image(s).
        model_version: Optional version of YOLO-World model to use. If not specified,
            uses the default version.
        confidence: Optional confidence threshold for detections. If not specified,
            uses the model's default threshold.

    Returns:
        List of dictionaries containing detection results for each input image.
        Each dictionary contains bounding boxes, class labels, and confidence scores
        for detected objects.

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    encoded_inference_inputs = await load_static_inference_input_async(
        inference_input=inference_input,
    )
    payload = self.__initialise_payload()
    payload["text"] = class_names
    if model_version is not None:
        payload["yolo_world_version_id"] = model_version
    if confidence is not None:
        payload["confidence"] = confidence
    url = self.__wrap_url_with_api_key(f"{self.__api_url}/yolo_world/infer")
    requests_data = prepare_requests_data(
        url=url,
        encoded_inference_inputs=encoded_inference_inputs,
        headers=DEFAULT_HEADERS,
        parameters=None,
        payload=payload,
        max_batch_size=1,
        image_placement=ImagePlacement.JSON,
    )
    return await execute_requests_packages_async(
        requests_data=requests_data,
        request_method=RequestMethod.POST,
        max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
    )

infer_on_stream(input_uri, model_id=None)

Run inference on a video stream or sequence of images.

Parameters:

Name Type Description Default
input_uri str

URI of the input stream or directory.

required
model_id Optional[str]

Model identifier to use for inference. Defaults to None.

None

Yields:

Type Description
Tuple[Union[str, int], ndarray, dict]

Generator[Tuple[Union[str, int], np.ndarray, dict], None, None]: Tuples of (frame reference, frame data, prediction).

Source code in inference_sdk/http/client.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def infer_on_stream(
    self,
    input_uri: str,
    model_id: Optional[str] = None,
) -> Generator[Tuple[Union[str, int], np.ndarray, dict], None, None]:
    """Run inference on a video stream or sequence of images.

    Args:
        input_uri (str): URI of the input stream or directory.
        model_id (Optional[str], optional): Model identifier to use for inference. Defaults to None.

    Yields:
        Generator[Tuple[Union[str, int], np.ndarray, dict], None, None]: Tuples of (frame reference, frame data, prediction).
    """
    for reference, frame in load_stream_inference_input(
        input_uri=input_uri,
        image_extensions=self.__inference_configuration.image_extensions_for_directory_scan,
    ):
        prediction = self.infer(
            inference_input=frame,
            model_id=model_id,
        )
        yield reference, frame, prediction

init(api_url, api_key=None) classmethod

Initialize a new InferenceHTTPClient instance.

Parameters:

Name Type Description Default
api_url str

The base URL for the inference API.

required
api_key Optional[str]

API key for authentication. Defaults to None.

None

Returns:

Name Type Description
InferenceHTTPClient InferenceHTTPClient

A new instance of the InferenceHTTPClient.

Source code in inference_sdk/http/client.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
@classmethod
def init(
    cls,
    api_url: str,
    api_key: Optional[str] = None,
) -> "InferenceHTTPClient":
    """Initialize a new InferenceHTTPClient instance.

    Args:
        api_url (str): The base URL for the inference API.
        api_key (Optional[str], optional): API key for authentication. Defaults to None.

    Returns:
        InferenceHTTPClient: A new instance of the InferenceHTTPClient.
    """
    return cls(api_url=api_url, api_key=api_key)

list_inference_pipelines()

Lists all active inference pipelines on the server.

This method retrieves information about all currently running inference pipelines on the server, including their IDs and status.

Returns:

Type Description
List[dict]

List[dict]: A list of dictionaries containing information about each active inference pipeline.

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@experimental(
    info="Video processing in inference server is under development. Breaking changes are possible."
)
@wrap_errors
def list_inference_pipelines(self) -> List[dict]:
    """Lists all active inference pipelines on the server.

    This method retrieves information about all currently running inference pipelines
    on the server, including their IDs and status.

    Returns:
        List[dict]: A list of dictionaries containing information about each active
            inference pipeline.

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    payload = {"api_key": self.__api_key}
    response = requests.get(
        f"{self.__api_url}/inference_pipelines/list",
        json=payload,
    )
    api_key_safe_raise_for_status(response=response)
    return response.json()

list_loaded_models()

List all models currently loaded on the server.

Returns:

Name Type Description
RegisteredModels RegisteredModels

Information about registered models.

Raises:

Type Description
WrongClientModeError

If not in API v1 mode.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
@wrap_errors
def list_loaded_models(self) -> RegisteredModels:
    """List all models currently loaded on the server.

    Returns:
        RegisteredModels: Information about registered models.

    Raises:
        WrongClientModeError: If not in API v1 mode.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    self.__ensure_v1_client_mode()
    response = requests.get(f"{self.__api_url}/model/registry")
    response.raise_for_status()
    response_payload = response.json()
    return RegisteredModels.from_dict(response_payload)

list_loaded_models_async() async

List all models currently loaded on the server asynchronously.

Returns:

Name Type Description
RegisteredModels RegisteredModels

Information about registered models.

Raises:

Type Description
WrongClientModeError

If not in API v1 mode.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
@wrap_errors_async
async def list_loaded_models_async(self) -> RegisteredModels:
    """List all models currently loaded on the server asynchronously.

    Returns:
        RegisteredModels: Information about registered models.

    Raises:
        WrongClientModeError: If not in API v1 mode.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    self.__ensure_v1_client_mode()
    async with aiohttp.ClientSession() as session:
        async with session.get(f"{self.__api_url}/model/registry") as response:
            response.raise_for_status()
            response_payload = await response.json()
            return RegisteredModels.from_dict(response_payload)

load_model(model_id, set_as_default=False)

Load a model onto the server.

Parameters:

Name Type Description Default
model_id str

The identifier of the model to load.

required
set_as_default bool

Whether to set this model as the default. Defaults to False.

False

Returns:

Name Type Description
RegisteredModels RegisteredModels

Updated information about registered models.

Raises:

Type Description
WrongClientModeError

If not in API v1 mode.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors
def load_model(
    self, model_id: str, set_as_default: bool = False
) -> RegisteredModels:
    """Load a model onto the server.

    Args:
        model_id (str): The identifier of the model to load.
        set_as_default (bool, optional): Whether to set this model as the default. Defaults to False.

    Returns:
        RegisteredModels: Updated information about registered models.

    Raises:
        WrongClientModeError: If not in API v1 mode.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    self.__ensure_v1_client_mode()
    de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
    response = requests.post(
        f"{self.__api_url}/model/add",
        json={
            "model_id": de_aliased_model_id,
            "api_key": self.__api_key,
        },
        headers=DEFAULT_HEADERS,
    )
    response.raise_for_status()
    response_payload = response.json()
    if set_as_default:
        self.__selected_model = de_aliased_model_id
    return RegisteredModels.from_dict(response_payload)

load_model_async(model_id, set_as_default=False) async

Load a model onto the server asynchronously.

Parameters:

Name Type Description Default
model_id str

The identifier of the model to load.

required
set_as_default bool

Whether to set this model as the default. Defaults to False.

False

Returns:

Name Type Description
RegisteredModels RegisteredModels

Updated information about registered models.

Raises:

Type Description
WrongClientModeError

If not in API v1 mode.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors_async
async def load_model_async(
    self, model_id: str, set_as_default: bool = False
) -> RegisteredModels:
    """Load a model onto the server asynchronously.

    Args:
        model_id (str): The identifier of the model to load.
        set_as_default (bool, optional): Whether to set this model as the default. Defaults to False.

    Returns:
        RegisteredModels: Updated information about registered models.

    Raises:
        WrongClientModeError: If not in API v1 mode.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    self.__ensure_v1_client_mode()
    de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
    payload = {
        "model_id": de_aliased_model_id,
        "api_key": self.__api_key,
    }
    async with aiohttp.ClientSession() as session:
        async with session.post(
            f"{self.__api_url}/model/add",
            json=payload,
            headers=DEFAULT_HEADERS,
        ) as response:
            response.raise_for_status()
            response_payload = await response.json()
    if set_as_default:
        self.__selected_model = de_aliased_model_id
    return RegisteredModels.from_dict(response_payload)

ocr_image(inference_input, model='doctr', version=None)

Run OCR on input image(s).

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) for OCR.

required
model str

OCR model to use ('doctr' or 'trocr'). Defaults to "doctr".

'doctr'
version Optional[str]

Model version to use. Defaults to None. For trocr, supported versions are: 'trocr-small-printed', 'trocr-base-printed', 'trocr-large-printed'.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: OCR results for the input image(s).

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors
def ocr_image(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
    model: str = "doctr",
    version: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Run OCR on input image(s).

    Args:
        inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for OCR.
        model (str, optional): OCR model to use ('doctr' or 'trocr'). Defaults to "doctr".
        version (Optional[str], optional): Model version to use. Defaults to None.
            For trocr, supported versions are: 'trocr-small-printed', 'trocr-base-printed', 'trocr-large-printed'.

    Returns:
        Union[dict, List[dict]]: OCR results for the input image(s).

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    encoded_inference_inputs = load_static_inference_input(
        inference_input=inference_input,
    )
    payload = self.__initialise_payload()
    if version:
        key = f"{model.lower()}_version_id"
        payload[key] = version
    model_path = resolve_ocr_path(model_name=model)
    url = self.__wrap_url_with_api_key(f"{self.__api_url}{model_path}")
    requests_data = prepare_requests_data(
        url=url,
        encoded_inference_inputs=encoded_inference_inputs,
        headers=DEFAULT_HEADERS,
        parameters=None,
        payload=payload,
        max_batch_size=1,
        image_placement=ImagePlacement.JSON,
    )
    responses = execute_requests_packages(
        requests_data=requests_data,
        request_method=RequestMethod.POST,
        max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
    )
    results = [r.json() for r in responses]
    return unwrap_single_element_list(sequence=results)

ocr_image_async(inference_input, model='doctr', version=None) async

Run OCR on input image(s) asynchronously.

Parameters:

Name Type Description Default
inference_input Union[ImagesReference, List[ImagesReference]]

Input image(s) for OCR.

required
model str

OCR model to use ('doctr' or 'trocr'). Defaults to "doctr".

'doctr'
version Optional[str]

Model version to use. Defaults to None. For trocr, supported versions are: 'trocr-small-printed', 'trocr-base-printed', 'trocr-large-printed'.

None

Returns:

Type Description
Union[dict, List[dict]]

Union[dict, List[dict]]: OCR results for the input image(s).

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors_async
async def ocr_image_async(
    self,
    inference_input: Union[ImagesReference, List[ImagesReference]],
    model: str = "doctr",
    version: Optional[str] = None,
) -> Union[dict, List[dict]]:
    """Run OCR on input image(s) asynchronously.

    Args:
        inference_input (Union[ImagesReference, List[ImagesReference]]): Input image(s) for OCR.
        model (str, optional): OCR model to use ('doctr' or 'trocr'). Defaults to "doctr".
        version (Optional[str], optional): Model version to use. Defaults to None.
            For trocr, supported versions are: 'trocr-small-printed', 'trocr-base-printed', 'trocr-large-printed'.

    Returns:
        Union[dict, List[dict]]: OCR results for the input image(s).

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    encoded_inference_inputs = await load_static_inference_input_async(
        inference_input=inference_input,
    )
    payload = self.__initialise_payload()
    if version:
        key = f"{model.lower()}_version_id"
        payload[key] = version
    model_path = resolve_ocr_path(model_name=model)
    url = self.__wrap_url_with_api_key(f"{self.__api_url}{model_path}")
    requests_data = prepare_requests_data(
        url=url,
        encoded_inference_inputs=encoded_inference_inputs,
        headers=DEFAULT_HEADERS,
        parameters=None,
        payload=payload,
        max_batch_size=1,
        image_placement=ImagePlacement.JSON,
    )
    responses = await execute_requests_packages_async(
        requests_data=requests_data,
        request_method=RequestMethod.POST,
        max_concurrent_requests=self.__inference_configuration.max_concurrent_requests,
    )
    return unwrap_single_element_list(sequence=responses)

pause_inference_pipeline(pipeline_id)

Pauses a running inference pipeline.

Sends a request to pause the specified inference pipeline. The pipeline must be currently running for this operation to succeed.

Parameters:

Name Type Description Default
pipeline_id str

The unique identifier of the inference pipeline to pause.

required

Returns:

Name Type Description
dict dict

A dictionary containing the response from the server about the pause operation.

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

ValueError

If pipeline_id is empty or None.

Source code in inference_sdk/http/client.py
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
@experimental(
    info="Video processing in inference server is under development. Breaking changes are possible."
)
@wrap_errors
def pause_inference_pipeline(self, pipeline_id: str) -> dict:
    """Pauses a running inference pipeline.

    Sends a request to pause the specified inference pipeline. The pipeline must be
    currently running for this operation to succeed.

    Args:
        pipeline_id: The unique identifier of the inference pipeline to pause.

    Returns:
        dict: A dictionary containing the response from the server about the pause operation.

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
        ValueError: If pipeline_id is empty or None.
    """
    self._ensure_pipeline_id_not_empty(pipeline_id=pipeline_id)
    payload = {"api_key": self.__api_key}
    response = requests.post(
        f"{self.__api_url}/inference_pipelines/{pipeline_id}/pause",
        json=payload,
    )
    api_key_safe_raise_for_status(response=response)
    return response.json()

resume_inference_pipeline(pipeline_id)

Resumes a paused inference pipeline.

Sends a request to resume the specified inference pipeline. The pipeline must be currently paused for this operation to succeed.

Parameters:

Name Type Description Default
pipeline_id str

The unique identifier of the inference pipeline to resume.

required

Returns:

Name Type Description
dict dict

A dictionary containing the response from the server about the resume operation.

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

ValueError

If pipeline_id is empty or None.

Source code in inference_sdk/http/client.py
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
@experimental(
    info="Video processing in inference server is under development. Breaking changes are possible."
)
@wrap_errors
def resume_inference_pipeline(self, pipeline_id: str) -> dict:
    """Resumes a paused inference pipeline.

    Sends a request to resume the specified inference pipeline. The pipeline must be
    currently paused for this operation to succeed.

    Args:
        pipeline_id: The unique identifier of the inference pipeline to resume.

    Returns:
        dict: A dictionary containing the response from the server about the resume operation.

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
        ValueError: If pipeline_id is empty or None.
    """
    self._ensure_pipeline_id_not_empty(pipeline_id=pipeline_id)
    payload = {"api_key": self.__api_key}
    response = requests.post(
        f"{self.__api_url}/inference_pipelines/{pipeline_id}/resume",
        json=payload,
    )
    api_key_safe_raise_for_status(response=response)
    return response.json()

run_workflow(workspace_name=None, workflow_id=None, specification=None, images=None, parameters=None, excluded_fields=None, use_cache=True, enable_profiling=False)

Run inference using a workflow specification.

Triggers inference from workflow specification at the inference HTTP side. Either (workspace_name and workflow_id) or workflow_specification must be provided. In the first case - definition of workflow will be fetched from Roboflow API, in the latter - workflow_specification will be used. images and parameters will be merged into workflow inputs, the distinction is made to make sure the SDK can easily serialise images and prepare a proper payload. Supported images are numpy arrays, PIL.Image and base64 images, links to images and local paths. excluded_fields will be added to request to filter out results of workflow execution at the server side.

Important! Method is not compatible with inference server <=0.9.18. Please migrate to newer version of the server before end of Q2 2024. Until that is done - use old method: infer_from_workflow(...).

Note

Method is not compatible with inference server <=0.9.18. Please migrate to newer version of the server before end of Q2 2024. Until that is done - use old method: infer_from_workflow(...).

Parameters:

Name Type Description Default
workspace_name Optional[str]

Name of the workspace containing the workflow. Defaults to None.

None
workflow_id Optional[str]

ID of the workflow. Defaults to None.

None
specification Optional[dict]

Direct workflow specification. Defaults to None.

None
images Optional[Dict[str, Any]]

Images to process. Defaults to None.

None
parameters Optional[Dict[str, Any]]

Additional parameters for the workflow. Defaults to None.

None
excluded_fields Optional[List[str]]

Fields to exclude from results. Defaults to None.

None
use_cache bool

Whether to use cached results. Defaults to True.

True
enable_profiling bool

Whether to enable profiling. Defaults to False.

False

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Results of the workflow execution.

Raises:

Type Description
InvalidParameterError

If neither workflow identifiers nor specification is provided.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors
def run_workflow(
    self,
    workspace_name: Optional[str] = None,
    workflow_id: Optional[str] = None,
    specification: Optional[dict] = None,
    images: Optional[Dict[str, Any]] = None,
    parameters: Optional[Dict[str, Any]] = None,
    excluded_fields: Optional[List[str]] = None,
    use_cache: bool = True,
    enable_profiling: bool = False,
) -> List[Dict[str, Any]]:
    """Run inference using a workflow specification.

    Triggers inference from workflow specification at the inference HTTP
    side. Either (`workspace_name` and `workflow_id`) or `workflow_specification` must be
    provided. In the first case - definition of workflow will be fetched
    from Roboflow API, in the latter - `workflow_specification` will be
    used. `images` and `parameters` will be merged into workflow inputs,
    the distinction is made to make sure the SDK can easily serialise
    images and prepare a proper payload. Supported images are numpy arrays,
    PIL.Image and base64 images, links to images and local paths.
    `excluded_fields` will be added to request to filter out results
    of workflow execution at the server side.

    **Important!**
    Method is not compatible with inference server <=0.9.18. Please migrate to newer version of
    the server before end of Q2 2024. Until that is done - use old method: infer_from_workflow(...).

    Note:
        Method is not compatible with inference server <=0.9.18. Please migrate to newer version of
        the server before end of Q2 2024. Until that is done - use old method: infer_from_workflow(...).

    Args:
        workspace_name (Optional[str], optional): Name of the workspace containing the workflow. Defaults to None.
        workflow_id (Optional[str], optional): ID of the workflow. Defaults to None.
        specification (Optional[dict], optional): Direct workflow specification. Defaults to None.
        images (Optional[Dict[str, Any]], optional): Images to process. Defaults to None.
        parameters (Optional[Dict[str, Any]], optional): Additional parameters for the workflow. Defaults to None.
        excluded_fields (Optional[List[str]], optional): Fields to exclude from results. Defaults to None.
        use_cache (bool, optional): Whether to use cached results. Defaults to True.
        enable_profiling (bool, optional): Whether to enable profiling. Defaults to False.

    Returns:
        List[Dict[str, Any]]: Results of the workflow execution.

    Raises:
        InvalidParameterError: If neither workflow identifiers nor specification is provided.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    return self._run_workflow(
        workspace_name=workspace_name,
        workflow_id=workflow_id,
        specification=specification,
        images=images,
        parameters=parameters,
        excluded_fields=excluded_fields,
        legacy_endpoints=False,
        use_cache=use_cache,
        enable_profiling=enable_profiling,
    )

select_api_v0()

Select API version 0 for client operations.

Returns:

Name Type Description
InferenceHTTPClient InferenceHTTPClient

The client instance with API v0 selected.

Source code in inference_sdk/http/client.py
265
266
267
268
269
270
271
272
def select_api_v0(self) -> "InferenceHTTPClient":
    """Select API version 0 for client operations.

    Returns:
        InferenceHTTPClient: The client instance with API v0 selected.
    """
    self.__client_mode = HTTPClientMode.V0
    return self

select_api_v1()

Select API version 1 for client operations.

Returns:

Name Type Description
InferenceHTTPClient InferenceHTTPClient

The client instance with API v1 selected.

Source code in inference_sdk/http/client.py
274
275
276
277
278
279
280
281
def select_api_v1(self) -> "InferenceHTTPClient":
    """Select API version 1 for client operations.

    Returns:
        InferenceHTTPClient: The client instance with API v1 selected.
    """
    self.__client_mode = HTTPClientMode.V1
    return self

select_model(model_id)

Select a model for inference operations.

Parameters:

Name Type Description Default
model_id str

The identifier of the model to select.

required

Returns:

Name Type Description
InferenceHTTPClient InferenceHTTPClient

The client instance with the selected model.

Source code in inference_sdk/http/client.py
311
312
313
314
315
316
317
318
319
320
321
def select_model(self, model_id: str) -> "InferenceHTTPClient":
    """Select a model for inference operations.

    Args:
        model_id (str): The identifier of the model to select.

    Returns:
        InferenceHTTPClient: The client instance with the selected model.
    """
    self.__selected_model = model_id
    return self

start_inference_pipeline_with_workflow(video_reference, workflow_specification=None, workspace_name=None, workflow_id=None, image_input_name='image', workflows_parameters=None, workflows_thread_pool_workers=4, cancel_thread_pool_tasks_on_exit=True, video_metadata_input_name='video_metadata', max_fps=None, source_buffer_filling_strategy='DROP_OLDEST', source_buffer_consumption_strategy='EAGER', video_source_properties=None, batch_collection_timeout=None, results_buffer_size=64)

Starts an inference pipeline using a workflow specification.

Parameters:

Name Type Description Default
video_reference Union[str, int, List[Union[str, int]]]

Path to video file, camera index, or list of video sources. Can be a string path, integer camera index, or list of either.

required
workflow_specification Optional[dict]

Optional workflow specification dictionary. Mutually exclusive with workspace_name/workflow_id.

None
workspace_name Optional[str]

Optional name of workspace containing workflow. Must be used with workflow_id.

None
workflow_id Optional[str]

Optional ID of workflow to use. Must be used with workspace_name.

None
image_input_name str

Name of the image input node in workflow. Defaults to "image".

'image'
workflows_parameters Optional[Dict[str, Any]]

Optional parameters to pass to workflow.

None
workflows_thread_pool_workers int

Number of worker threads for workflow execution. Defaults to 4.

4
cancel_thread_pool_tasks_on_exit bool

Whether to cancel pending tasks when exiting. Defaults to True.

True
video_metadata_input_name str

Name of video metadata input in workflow. Defaults to "video_metadata".

'video_metadata'
max_fps Optional[Union[float, int]]

Optional maximum FPS to process video at.

None
source_buffer_filling_strategy Optional[BufferFillingStrategy]

Strategy for filling source buffer when full. One of: "WAIT", "DROP_OLDEST", "ADAPTIVE_DROP_OLDEST", "DROP_LATEST", "ADAPTIVE_DROP_LATEST". Defaults to "DROP_OLDEST".

'DROP_OLDEST'
source_buffer_consumption_strategy Optional[BufferConsumptionStrategy]

Strategy for consuming from source buffer. One of: "LAZY", "EAGER". Defaults to "EAGER".

'EAGER'
video_source_properties Optional[Dict[str, float]]

Optional dictionary of video source properties.

None
batch_collection_timeout Optional[float]

Optional timeout for batch collection in seconds.

None
results_buffer_size int

Size of results buffer. Defaults to 64.

64

Returns:

Name Type Description
dict dict

Response containing pipeline initialization details.

Raises:

Type Description
InvalidParameterError

If workflow specification parameters are invalid.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@experimental(
    info="Video processing in inference server is under development. Breaking changes are possible."
)
@wrap_errors
def start_inference_pipeline_with_workflow(
    self,
    video_reference: Union[str, int, List[Union[str, int]]],
    workflow_specification: Optional[dict] = None,
    workspace_name: Optional[str] = None,
    workflow_id: Optional[str] = None,
    image_input_name: str = "image",
    workflows_parameters: Optional[Dict[str, Any]] = None,
    workflows_thread_pool_workers: int = 4,
    cancel_thread_pool_tasks_on_exit: bool = True,
    video_metadata_input_name: str = "video_metadata",
    max_fps: Optional[Union[float, int]] = None,
    source_buffer_filling_strategy: Optional[BufferFillingStrategy] = "DROP_OLDEST",
    source_buffer_consumption_strategy: Optional[
        BufferConsumptionStrategy
    ] = "EAGER",
    video_source_properties: Optional[Dict[str, float]] = None,
    batch_collection_timeout: Optional[float] = None,
    results_buffer_size: int = 64,
) -> dict:
    """Starts an inference pipeline using a workflow specification.

    Args:
        video_reference: Path to video file, camera index, or list of video sources.
            Can be a string path, integer camera index, or list of either.
        workflow_specification: Optional workflow specification dictionary. Mutually
            exclusive with workspace_name/workflow_id.
        workspace_name: Optional name of workspace containing workflow. Must be used
            with workflow_id.
        workflow_id: Optional ID of workflow to use. Must be used with workspace_name.
        image_input_name: Name of the image input node in workflow. Defaults to "image".
        workflows_parameters: Optional parameters to pass to workflow.
        workflows_thread_pool_workers: Number of worker threads for workflow execution.
            Defaults to 4.
        cancel_thread_pool_tasks_on_exit: Whether to cancel pending tasks when exiting.
            Defaults to True.
        video_metadata_input_name: Name of video metadata input in workflow.
            Defaults to "video_metadata".
        max_fps: Optional maximum FPS to process video at.
        source_buffer_filling_strategy: Strategy for filling source buffer when full.
            One of: "WAIT", "DROP_OLDEST", "ADAPTIVE_DROP_OLDEST", "DROP_LATEST",
            "ADAPTIVE_DROP_LATEST". Defaults to "DROP_OLDEST".
        source_buffer_consumption_strategy: Strategy for consuming from source buffer.
            One of: "LAZY", "EAGER". Defaults to "EAGER".
        video_source_properties: Optional dictionary of video source properties.
        batch_collection_timeout: Optional timeout for batch collection in seconds.
        results_buffer_size: Size of results buffer. Defaults to 64.

    Returns:
        dict: Response containing pipeline initialization details.

    Raises:
        InvalidParameterError: If workflow specification parameters are invalid.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    named_workflow_specified = (workspace_name is not None) and (
        workflow_id is not None
    )
    if not (named_workflow_specified != (workflow_specification is not None)):
        raise InvalidParameterError(
            "Parameters (`workspace_name`, `workflow_id`) can be used mutually exclusive with "
            "`workflow_specification`, but at least one must be set."
        )
    payload = {
        "api_key": self.__api_key,
        "video_configuration": {
            "type": "VideoConfiguration",
            "video_reference": video_reference,
            "max_fps": max_fps,
            "source_buffer_filling_strategy": source_buffer_filling_strategy,
            "source_buffer_consumption_strategy": source_buffer_consumption_strategy,
            "video_source_properties": video_source_properties,
            "batch_collection_timeout": batch_collection_timeout,
        },
        "processing_configuration": {
            "type": "WorkflowConfiguration",
            "workflow_specification": workflow_specification,
            "workspace_name": workspace_name,
            "workflow_id": workflow_id,
            "image_input_name": image_input_name,
            "workflows_parameters": workflows_parameters,
            "workflows_thread_pool_workers": workflows_thread_pool_workers,
            "cancel_thread_pool_tasks_on_exit": cancel_thread_pool_tasks_on_exit,
            "video_metadata_input_name": video_metadata_input_name,
        },
        "sink_configuration": {
            "type": "MemorySinkConfiguration",
            "results_buffer_size": results_buffer_size,
        },
    }
    response = requests.post(
        f"{self.__api_url}/inference_pipelines/initialise",
        json=payload,
    )
    response.raise_for_status()
    return response.json()

terminate_inference_pipeline(pipeline_id)

Terminates a running inference pipeline.

Sends a request to terminate the specified inference pipeline. This will stop all processing and free up associated resources.

Parameters:

Name Type Description Default
pipeline_id str

The unique identifier of the inference pipeline to terminate.

required

Returns:

Name Type Description
dict dict

A dictionary containing the response from the server about the termination operation.

Raises:

Type Description
HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

ValueError

If pipeline_id is empty or None.

Source code in inference_sdk/http/client.py
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
@experimental(
    info="Video processing in inference server is under development. Breaking changes are possible."
)
@wrap_errors
def terminate_inference_pipeline(self, pipeline_id: str) -> dict:
    """Terminates a running inference pipeline.

    Sends a request to terminate the specified inference pipeline. This will stop all
    processing and free up associated resources.

    Args:
        pipeline_id: The unique identifier of the inference pipeline to terminate.

    Returns:
        dict: A dictionary containing the response from the server about the termination operation.

    Raises:
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
        ValueError: If pipeline_id is empty or None.
    """
    self._ensure_pipeline_id_not_empty(pipeline_id=pipeline_id)
    payload = {"api_key": self.__api_key}
    response = requests.post(
        f"{self.__api_url}/inference_pipelines/{pipeline_id}/terminate",
        json=payload,
    )
    api_key_safe_raise_for_status(response=response)
    return response.json()

unload_model(model_id)

Unload a model from the server.

Parameters:

Name Type Description Default
model_id str

The identifier of the model to unload.

required

Returns:

Name Type Description
RegisteredModels RegisteredModels

Updated information about registered models.

Raises:

Type Description
WrongClientModeError

If not in API v1 mode.

HTTPCallErrorError

If there is an error in the HTTP call.

HTTPClientError

If there is an error with the server connection.

Source code in inference_sdk/http/client.py
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
@wrap_errors
def unload_model(self, model_id: str) -> RegisteredModels:
    """Unload a model from the server.

    Args:
        model_id (str): The identifier of the model to unload.

    Returns:
        RegisteredModels: Updated information about registered models.

    Raises:
        WrongClientModeError: If not in API v1 mode.
        HTTPCallErrorError: If there is an error in the HTTP call.
        HTTPClientError: If there is an error with the server connection.
    """
    self.__ensure_v1_client_mode()
    de_aliased_model_id = resolve_roboflow_model_alias(model_id=model_id)
    response = requests.post(
        f"{self.__api_url}/model/remove",
        json={
            "model_id": de_aliased_model_id,
        },
        headers=DEFAULT_HEADERS,
    )
    response.raise_for_status()
    response_payload = response.json()
    if (
        de_aliased_model_id == self.__selected_model
        or model_id == self.__selected_model
    ):
        self.__selected_model = None
    return RegisteredModels.from_dict(response_payload)

use_api_v0()

Temporarily use API version 0 for client operations.

Yields:

Type Description
InferenceHTTPClient

Generator[InferenceHTTPClient, None, None]: The client instance temporarily using API v0.

Source code in inference_sdk/http/client.py
283
284
285
286
287
288
289
290
291
292
293
294
295
@contextmanager
def use_api_v0(self) -> Generator["InferenceHTTPClient", None, None]:
    """Temporarily use API version 0 for client operations.

    Yields:
        Generator[InferenceHTTPClient, None, None]: The client instance temporarily using API v0.
    """
    previous_client_mode = self.__client_mode
    self.__client_mode = HTTPClientMode.V0
    try:
        yield self
    finally:
        self.__client_mode = previous_client_mode

use_api_v1()

Temporarily use API version 1 for client operations.

Yields:

Type Description
InferenceHTTPClient

Generator[InferenceHTTPClient, None, None]: The client instance temporarily using API v1.

Source code in inference_sdk/http/client.py
297
298
299
300
301
302
303
304
305
306
307
308
309
@contextmanager
def use_api_v1(self) -> Generator["InferenceHTTPClient", None, None]:
    """Temporarily use API version 1 for client operations.

    Yields:
        Generator[InferenceHTTPClient, None, None]: The client instance temporarily using API v1.
    """
    previous_client_mode = self.__client_mode
    self.__client_mode = HTTPClientMode.V1
    try:
        yield self
    finally:
        self.__client_mode = previous_client_mode

use_configuration(inference_configuration)

Temporarily use a different inference configuration.

Parameters:

Name Type Description Default
inference_configuration InferenceConfiguration

The temporary configuration to use.

required

Yields:

Type Description
InferenceHTTPClient

Generator[InferenceHTTPClient, None, None]: The client instance with temporary configuration.

Source code in inference_sdk/http/client.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
@contextmanager
def use_configuration(
    self, inference_configuration: InferenceConfiguration
) -> Generator["InferenceHTTPClient", None, None]:
    """Temporarily use a different inference configuration.

    Args:
        inference_configuration (InferenceConfiguration): The temporary configuration to use.

    Yields:
        Generator[InferenceHTTPClient, None, None]: The client instance with temporary configuration.
    """
    previous_configuration = self.__inference_configuration
    self.__inference_configuration = inference_configuration
    try:
        yield self
    finally:
        self.__inference_configuration = previous_configuration

use_model(model_id)

Temporarily use a specific model for inference operations.

Parameters:

Name Type Description Default
model_id str

The identifier of the model to use.

required

Yields:

Type Description
InferenceHTTPClient

Generator[InferenceHTTPClient, None, None]: The client instance temporarily using the specified model.

Source code in inference_sdk/http/client.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
@contextmanager
def use_model(self, model_id: str) -> Generator["InferenceHTTPClient", None, None]:
    """Temporarily use a specific model for inference operations.

    Args:
        model_id (str): The identifier of the model to use.

    Yields:
        Generator[InferenceHTTPClient, None, None]: The client instance temporarily using the specified model.
    """
    previous_model = self.__selected_model
    self.__selected_model = model_id
    try:
        yield self
    finally:
        self.__selected_model = previous_model