xinference-client 4.1.0__tar.gz → 4.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {xinference_client-4.1.0/xinference_client.egg-info → xinference_client-4.2.0}/PKG-INFO +1 -1
  2. {xinference_client-4.1.0 → xinference_client-4.2.0}/tests/test_async_client.py +5 -5
  3. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client/_version.py +3 -3
  4. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client/client/common.py +19 -2
  5. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client/client/restful/async_restful_client.py +157 -34
  6. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client/client/restful/restful_client.py +99 -10
  7. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client/types.py +17 -0
  8. {xinference_client-4.1.0 → xinference_client-4.2.0/xinference_client.egg-info}/PKG-INFO +1 -1
  9. {xinference_client-4.1.0 → xinference_client-4.2.0}/LICENSE +0 -0
  10. {xinference_client-4.1.0 → xinference_client-4.2.0}/MANIFEST.in +0 -0
  11. {xinference_client-4.1.0 → xinference_client-4.2.0}/README.md +0 -0
  12. {xinference_client-4.1.0 → xinference_client-4.2.0}/pyproject.toml +0 -0
  13. {xinference_client-4.1.0 → xinference_client-4.2.0}/setup.cfg +0 -0
  14. {xinference_client-4.1.0 → xinference_client-4.2.0}/setup.py +0 -0
  15. {xinference_client-4.1.0 → xinference_client-4.2.0}/tests/test_async_client_cleanup.py +0 -0
  16. {xinference_client-4.1.0 → xinference_client-4.2.0}/third_party/inference/xinference/thirdparty/matcha/utils/monotonic_align/core.pyx +0 -0
  17. {xinference_client-4.1.0 → xinference_client-4.2.0}/versioneer.py +0 -0
  18. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client/__init__.py +0 -0
  19. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client/_compat.py +0 -0
  20. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client/client/__init__.py +0 -0
  21. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client/client/restful/__init__.py +0 -0
  22. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client/fields.py +0 -0
  23. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client.egg-info/SOURCES.txt +0 -0
  24. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client.egg-info/dependency_links.txt +0 -0
  25. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client.egg-info/not-zip-safe +0 -0
  26. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client.egg-info/requires.txt +0 -0
  27. {xinference_client-4.1.0 → xinference_client-4.2.0}/xinference_client.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xinference-client
3
- Version: 4.1.0
3
+ Version: 4.2.0
4
4
  Summary: Client for Xinference
5
5
  Home-page: https://github.com/xorbitsai/inference-client
6
6
  Author: Qin Xuye
@@ -5,17 +5,17 @@ from xinference_client import AsyncRESTfulClient
5
5
 
6
6
 
7
7
  @pytest.mark.asyncio
8
- async def test_list_models_and_explicit_close(monkeypatch):
9
- # Authentication discovery is synchronous; isolate it from the async server.
10
- monkeypatch.setattr(
11
- AsyncRESTfulClient, "_check_cluster_authenticated", lambda self: None
12
- )
8
+ async def test_list_models_and_explicit_close():
13
9
  model = {"id": "test-model", "model_type": "LLM"}
14
10
 
15
11
  async def list_models(request):
16
12
  return web.json_response({"data": [model]})
17
13
 
14
+ async def cluster_auth(request):
15
+ return web.json_response({"auth": False})
16
+
18
17
  app = web.Application()
18
+ app.router.add_get("/v1/cluster/auth", cluster_auth)
19
19
  app.router.add_get("/v1/models", list_models)
20
20
  runner = web.AppRunner(app)
21
21
  await runner.setup()
@@ -8,11 +8,11 @@ import json
8
8
 
9
9
  version_json = '''
10
10
  {
11
- "date": "2026-10-25T12:29:53+0800",
11
+ "date": "2026-11-07T16:20:12+0800",
12
12
  "dirty": false,
13
13
  "error": null,
14
- "full-revisionid": "63f5e9dd6df9f0bc9a91569268e7528883255b2f",
15
- "version": "4.1.0"
14
+ "full-revisionid": "126f5b56ffbab1bda41d00c36731e26a91773281",
15
+ "version": "4.2.0"
16
16
  }
17
17
  ''' # END VERSION_JSON
18
18
 
@@ -17,6 +17,18 @@ import json
17
17
  import os
18
18
  from typing import Any, AsyncIterator, Iterator, Union
19
19
 
20
+ # (connect, read) seconds for fetching an image URL, as used by the server.
21
+ # The read timeout limits inactivity, not the total download time.
22
+ IMAGE_DOWNLOAD_TIMEOUT = (10, 30)
23
+
24
+
25
+ def normalize_endpoint(endpoint: str) -> str:
26
+ return endpoint.rstrip("/")
27
+
28
+
29
+ def is_http_url(value: str) -> bool:
30
+ return value.lower().startswith(("http://", "https://"))
31
+
20
32
 
21
33
  def encode_world_reference(reference: Union[str, bytes], media_type: str) -> str:
22
34
  if isinstance(reference, str) and not os.path.isfile(reference):
@@ -71,7 +83,7 @@ def streaming_response_iterator(
71
83
  if line.startswith(b"data:"):
72
84
  json_str = line[len(b"data:") :].strip()
73
85
  if json_str == b"[DONE]":
74
- continue
86
+ break
75
87
  data = json.loads(json_str.decode("utf-8"))
76
88
  error = data.get("error", None)
77
89
  if error is not None:
@@ -81,6 +93,8 @@ def streaming_response_iterator(
81
93
 
82
94
  async def async_streaming_response_iterator(
83
95
  response_or_lines: Any,
96
+ *,
97
+ _prime: bool = False,
84
98
  ) -> AsyncIterator[Any]:
85
99
  """
86
100
  Create an AsyncIterator to handle the streaming type of generation.
@@ -110,12 +124,15 @@ async def async_streaming_response_iterator(
110
124
  )
111
125
  response_lines = response.content if response is not None else response_or_lines
112
126
  try:
127
+ if _prime:
128
+ # Enter the cleanup scope before handing the stream to the caller.
129
+ yield None
113
130
  async for line in response_lines:
114
131
  line = line.strip()
115
132
  if line.startswith(b"data:"):
116
133
  json_str = line[len(b"data:") :].strip()
117
134
  if json_str == b"[DONE]":
118
- continue
135
+ break
119
136
  data = json.loads(json_str.decode("utf-8"))
120
137
  error = data.get("error", None)
121
138
  if error is not None:
@@ -19,9 +19,12 @@ from urllib.parse import quote
19
19
  import aiohttp
20
20
 
21
21
  from ..common import (
22
+ IMAGE_DOWNLOAD_TIMEOUT,
22
23
  async_streaming_response_iterator,
23
24
  convert_float_to_int_or_str,
24
25
  encode_world_reference,
26
+ is_http_url,
27
+ normalize_endpoint,
25
28
  )
26
29
 
27
30
  if TYPE_CHECKING:
@@ -71,6 +74,12 @@ async def _release_response(response: aiohttp.ClientResponse):
71
74
  await response.wait_for_close()
72
75
 
73
76
 
77
+ async def _streaming_response(response: aiohttp.ClientResponse) -> AsyncIterator[Any]:
78
+ stream = async_streaming_response_iterator(response, _prime=True)
79
+ await anext(stream)
80
+ return stream
81
+
82
+
74
83
  def _schedule_session_close(client: Any) -> None:
75
84
  if not getattr(client, "session", None):
76
85
  return
@@ -416,6 +425,29 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
416
425
  await _release_response(response)
417
426
  return response_data
418
427
 
428
+ async def _download_if_url(self, image: Any) -> Any:
429
+ """Download an http(s) URL; paths, bytes and file objects pass through."""
430
+ if not (isinstance(image, str) and is_http_url(image)):
431
+ return image
432
+ # No auth headers: the Xinference credentials must not reach the image host.
433
+ # A request timeout replaces the session's, so carry its total over.
434
+ timeout = aiohttp.ClientTimeout(
435
+ total=self.session.timeout.total,
436
+ sock_connect=IMAGE_DOWNLOAD_TIMEOUT[0],
437
+ sock_read=IMAGE_DOWNLOAD_TIMEOUT[1],
438
+ )
439
+ try:
440
+ response = await self.session.get(image, timeout=timeout)
441
+ try:
442
+ response.raise_for_status()
443
+ return await response.read()
444
+ finally:
445
+ await _release_response(response)
446
+ except (aiohttp.ClientError, asyncio.TimeoutError) as error:
447
+ raise RuntimeError(
448
+ f"Failed to download an image for editing, detail: {error}"
449
+ ) from error
450
+
419
451
  async def image_edit(
420
452
  self,
421
453
  images: Union[Union[str, bytes], List[Union[str, bytes]]],
@@ -476,6 +508,12 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
476
508
  )
477
509
  """
478
510
  url = f"{self._base_url}/v1/images/edits"
511
+ # The route takes uploaded files only, so URLs are downloaded here.
512
+ if isinstance(images, list):
513
+ images = [await self._download_if_url(image) for image in images]
514
+ else:
515
+ images = await self._download_if_url(images)
516
+ mask = await self._download_if_url(mask)
479
517
  params = {
480
518
  "model": self._model_uid,
481
519
  "prompt": prompt,
@@ -935,7 +973,7 @@ class AsyncRESTfulGenerateModelHandle(AsyncRESTfulModelHandle):
935
973
  )
936
974
 
937
975
  if stream:
938
- return async_streaming_response_iterator(response)
976
+ return await _streaming_response(response)
939
977
  response_data = await response.json()
940
978
  await _release_response(response)
941
979
  return response_data
@@ -1016,7 +1054,7 @@ class AsyncRESTfulChatModelHandle(AsyncRESTfulGenerateModelHandle):
1016
1054
  )
1017
1055
 
1018
1056
  if stream:
1019
- return async_streaming_response_iterator(response)
1057
+ return await _streaming_response(response)
1020
1058
 
1021
1059
  response_data = await response.json()
1022
1060
  await _release_response(response)
@@ -1318,29 +1356,37 @@ class AsyncRESTfulFlexibleModelHandle(AsyncRESTfulModelHandle):
1318
1356
 
1319
1357
  class AsyncClient:
1320
1358
  def __init__(self, base_url, api_key: Optional[str] = None):
1321
- self.base_url = base_url
1359
+ self.base_url = normalize_endpoint(base_url)
1360
+ self._api_key = api_key
1322
1361
  self._headers: Dict[str, str] = {}
1323
- self._cluster_authed = False
1362
+ # None until the first request has probed the cluster (_ensure_initialized).
1363
+ self._cluster_authed: Optional[bool] = None
1364
+ self._init_task: Optional["asyncio.Task[Optional[Exception]]"] = None
1324
1365
  self.timeout = aiohttp.ClientTimeout(total=1800)
1325
1366
  self._session_loop = asyncio.get_running_loop()
1326
1367
  self.session = aiohttp.ClientSession(
1327
1368
  connector=aiohttp.TCPConnector(force_close=True), timeout=self.timeout
1328
1369
  )
1329
- self._check_cluster_authenticated()
1330
- if api_key is not None and self._cluster_authed:
1331
- self._headers["Authorization"] = f"Bearer {api_key}"
1332
1370
 
1333
1371
  async def close(self):
1334
- """Close the AsyncClient session."""
1335
- if self.session:
1336
- await self.session.close()
1337
- self.session = None
1372
+ """Stop initialization and close the AsyncClient session."""
1373
+ init_task = getattr(self, "_init_task", None)
1374
+ try:
1375
+ if init_task is not None:
1376
+ if not init_task.done():
1377
+ init_task.cancel()
1378
+ await asyncio.gather(init_task, return_exceptions=True)
1379
+ finally:
1380
+ self._init_task = None
1381
+ if self.session:
1382
+ await self.session.close()
1383
+ self.session = None
1338
1384
 
1339
1385
  def __del__(self):
1340
1386
  _schedule_session_close(self)
1341
1387
 
1342
1388
  def _set_token(self, token: Optional[str]):
1343
- if not self._cluster_authed or token is None:
1389
+ if self._cluster_authed is False or token is None:
1344
1390
  return
1345
1391
  self._headers["Authorization"] = f"Bearer {token}"
1346
1392
 
@@ -1351,32 +1397,61 @@ class AsyncClient:
1351
1397
  else None
1352
1398
  )
1353
1399
 
1354
- def _check_cluster_authenticated(self):
1355
- import requests
1356
-
1357
- session = requests.Session()
1400
+ async def _check_cluster_authenticated(self) -> bool:
1358
1401
  url = f"{self.base_url}/v1/cluster/auth"
1359
- response = session.get(url)
1402
+ response = await self.session.get(url)
1360
1403
  # compatible with old version of xinference
1361
- if response.status_code == 404:
1362
- self._cluster_authed = False
1363
- else:
1364
- if response.status_code != 200:
1365
- response_data = response.json()
1366
- raise RuntimeError(
1367
- f"Failed to get cluster information, detail: {response_data['detail']}"
1368
- )
1369
- response_data = response.json()
1370
- self._cluster_authed = bool(response_data["auth"])
1404
+ if response.status == 404:
1405
+ await _release_response(response)
1406
+ return False
1407
+ if response.status != 200:
1408
+ raise RuntimeError(
1409
+ f"Failed to get cluster information, detail: {await _get_error_string(response)}"
1410
+ )
1411
+ response_data = await response.json()
1412
+ await _release_response(response)
1413
+ return bool(response_data["auth"])
1414
+
1415
+ async def _ensure_initialized(self) -> None:
1416
+ """Probe the cluster before the first request, without blocking the loop.
1417
+
1418
+ Concurrent first requests await one probe task and get its result or its
1419
+ error. The task is shielded, so cancelling one request does not cancel the
1420
+ probe for the others. A failed probe is not remembered: the next request
1421
+ starts a new one.
1422
+ """
1423
+ if self._cluster_authed is not None:
1424
+ return
1425
+ if self._init_task is None or self._init_task.done():
1426
+ self._init_task = asyncio.create_task(self._initialize())
1427
+ error = await asyncio.shield(self._init_task)
1428
+ if error is not None:
1429
+ raise error
1430
+
1431
+ async def _initialize(self) -> Optional[Exception]:
1432
+ # Returns the probe's error instead of raising it: if every caller was
1433
+ # cancelled, nobody would retrieve a raised one and asyncio logs that.
1434
+ # The result is stored only after the probe and the API key were handled.
1435
+ try:
1436
+ authed = await self._check_cluster_authenticated()
1437
+ if not authed:
1438
+ # A token set before the probe only applies to an auth cluster.
1439
+ self._headers.pop("Authorization", None)
1440
+ elif self._api_key is not None:
1441
+ # A token set before the probe is newer than the API key.
1442
+ self._headers.setdefault("Authorization", f"Bearer {self._api_key}")
1443
+ self._cluster_authed = authed
1444
+ return None
1445
+ except Exception as error:
1446
+ return error
1371
1447
 
1372
1448
  async def vllm_models(self) -> Dict[str, Any]:
1449
+ await self._ensure_initialized()
1373
1450
  url = f"{self.base_url}/v1/models/vllm-supported"
1374
1451
  response = await self.session.get(url, headers=self._headers)
1375
1452
  if response.status != 200:
1376
- response_data = await response.json()
1377
- await _release_response(response)
1378
1453
  raise RuntimeError(
1379
- f"Failed to get cluster information, detail: {response_data['detail']}"
1454
+ f"Failed to get cluster information, detail: {await _get_error_string(response)}"
1380
1455
  )
1381
1456
 
1382
1457
  try:
@@ -1387,6 +1462,7 @@ class AsyncClient:
1387
1462
  raise RuntimeError(f"Error parsing JSON response: {e}")
1388
1463
 
1389
1464
  async def login(self, username: str, password: str):
1465
+ await self._ensure_initialized()
1390
1466
  if not self._cluster_authed:
1391
1467
  return
1392
1468
  url = f"{self.base_url}/token"
@@ -1395,10 +1471,8 @@ class AsyncClient:
1395
1471
 
1396
1472
  response = await self.session.post(url, json=payload)
1397
1473
  if response.status != 200:
1398
- response_data = await response.json()
1399
- await _release_response(response)
1400
1474
  raise RuntimeError(
1401
- f"Failed to get cluster information, detail: {response_data['detail']}"
1475
+ f"Failed to get cluster information, detail: {await _get_error_string(response)}"
1402
1476
  )
1403
1477
 
1404
1478
  response_data = await response.json()
@@ -1418,6 +1492,7 @@ class AsyncClient:
1418
1492
 
1419
1493
  """
1420
1494
 
1495
+ await self._ensure_initialized()
1421
1496
  url = f"{self.base_url}/v1/models"
1422
1497
 
1423
1498
  response = await self.session.get(url, headers=self._headers)
@@ -1523,6 +1598,7 @@ class AsyncClient:
1523
1598
 
1524
1599
  """
1525
1600
 
1601
+ await self._ensure_initialized()
1526
1602
  url = f"{self.base_url}/v1/models"
1527
1603
 
1528
1604
  # convert float to int or string since the RESTful API does not accept float.
@@ -1574,6 +1650,7 @@ class AsyncClient:
1574
1650
  return response_data["model_uid"]
1575
1651
 
1576
1652
  async def get_autostart_config(self) -> Dict:
1653
+ await self._ensure_initialized()
1577
1654
  url = f"{self.base_url}/v1/autostart/models"
1578
1655
  response = await self.session.get(url, headers=self._headers)
1579
1656
  if response.status != 200:
@@ -1585,6 +1662,7 @@ class AsyncClient:
1585
1662
  return response_data
1586
1663
 
1587
1664
  async def get_autostart_model_summary(self) -> Dict:
1665
+ await self._ensure_initialized()
1588
1666
  url = f"{self.base_url}/v1/autostart/models/summary"
1589
1667
  response = await self.session.get(url, headers=self._headers)
1590
1668
  if response.status != 200:
@@ -1596,6 +1674,7 @@ class AsyncClient:
1596
1674
  return response_data
1597
1675
 
1598
1676
  async def upsert_autostart_model(self, entry: Dict) -> Dict:
1677
+ await self._ensure_initialized()
1599
1678
  url = f"{self.base_url}/v1/autostart/models"
1600
1679
  response = await self.session.post(url, json=entry, headers=self._headers)
1601
1680
  if response.status != 200:
@@ -1607,6 +1686,7 @@ class AsyncClient:
1607
1686
  return response_data
1608
1687
 
1609
1688
  async def remove_autostart_model(self, model_uid: str) -> Dict:
1689
+ await self._ensure_initialized()
1610
1690
  url = f"{self.base_url}/v1/autostart/models/{quote(model_uid, safe='')}"
1611
1691
  response = await self.session.delete(url, headers=self._headers)
1612
1692
  if response.status != 200:
@@ -1626,10 +1706,12 @@ class AsyncClient:
1626
1706
  ) -> Dict[str, Any]:
1627
1707
  """Start an asynchronous parameter reload with the same model UID.
1628
1708
 
1629
- Engine changes require launch-time ``enable_weight_cache=True``;
1709
+ Engine changes require weight retention enabled at launch (automatic
1710
+ on supported configurations, or ``enable_weight_cache=True``);
1630
1711
  a standalone ``reasoning_content`` update does not. Use
1631
1712
  ``get_model_reload_status`` to wait for ready/error after HTTP 202.
1632
1713
  """
1714
+ await self._ensure_initialized()
1633
1715
  url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/reload"
1634
1716
  payload = {"model_config": model_config, "drain_timeout": drain_timeout}
1635
1717
  if python_executable is not None:
@@ -1647,8 +1729,23 @@ class AsyncClient:
1647
1729
  await _release_response(response)
1648
1730
  return data
1649
1731
 
1732
+ async def get_model_runtime_info(self, model_uid: str) -> Dict[str, Any]:
1733
+ """Return runtime_context_length (tokens, or None) and per-replica limits."""
1734
+ await self._ensure_initialized()
1735
+ url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/runtime"
1736
+ response = await self.session.get(url, headers=self._headers)
1737
+ if response.status != 200:
1738
+ raise RuntimeError(
1739
+ f"Failed to get model runtime info, detail: {await _get_error_string(response)}"
1740
+ )
1741
+ try:
1742
+ return await response.json()
1743
+ finally:
1744
+ await _release_response(response)
1745
+
1650
1746
  async def get_model_reload_status(self, model_uid: str) -> Dict[str, Any]:
1651
1747
  """Return the latest reload operation, including its stage and error."""
1748
+ await self._ensure_initialized()
1652
1749
  url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/reload"
1653
1750
  response = await self.session.get(url, headers=self._headers)
1654
1751
  if response.status != 200:
@@ -1661,6 +1758,7 @@ class AsyncClient:
1661
1758
 
1662
1759
  async def get_model_reload_config(self, model_uid: str) -> Dict[str, Any]:
1663
1760
  """Return editable parameters, their types and current explicit values."""
1761
+ await self._ensure_initialized()
1664
1762
  url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/reload/config"
1665
1763
  response = await self.session.get(url, headers=self._headers)
1666
1764
  if response.status != 200:
@@ -1687,6 +1785,7 @@ class AsyncClient:
1687
1785
 
1688
1786
  """
1689
1787
 
1788
+ await self._ensure_initialized()
1690
1789
  url = f"{self.base_url}/v1/models/{model_uid}"
1691
1790
 
1692
1791
  response = await self.session.delete(url, headers=self._headers)
@@ -1734,6 +1833,7 @@ class AsyncClient:
1734
1833
  A single-replica result, or ``{"replica": int, "replicas": list}``
1735
1834
  when more than one replica is requested.
1736
1835
  """
1836
+ await self._ensure_initialized()
1737
1837
  url = f"{self.base_url}/v1/models/{model_uid}/replicas"
1738
1838
  payload: Dict[str, Any] = {}
1739
1839
  if replica_config is not None:
@@ -1756,6 +1856,7 @@ class AsyncClient:
1756
1856
  async def terminate_model_replica(self, model_uid: str, replica_id: int) -> int:
1757
1857
  """Terminate a specific replica of a running model."""
1758
1858
 
1859
+ await self._ensure_initialized()
1759
1860
  url = f"{self.base_url}/v1/models/{model_uid}/replicas/{replica_id}"
1760
1861
 
1761
1862
  response = await self.session.delete(url, headers=self._headers)
@@ -1787,6 +1888,7 @@ class AsyncClient:
1787
1888
  RuntimeError
1788
1889
  Report failure to get the wanted model with given model_uid. Provide details of failure through error message.
1789
1890
  """
1891
+ await self._ensure_initialized()
1790
1892
  url = f"{self.base_url}/v1/models/{model_uid}/progress"
1791
1893
 
1792
1894
  response = await self.session.get(url, headers=self._headers)
@@ -1812,6 +1914,7 @@ class AsyncClient:
1812
1914
  RuntimeError
1813
1915
  Report failure to get the wanted model with given model_uid. Provide details of failure through error message.
1814
1916
  """
1917
+ await self._ensure_initialized()
1815
1918
  url = f"{self.base_url}/v1/models/{model_uid}/cancel"
1816
1919
 
1817
1920
  response = await self.session.post(url, headers=self._headers)
@@ -1822,6 +1925,7 @@ class AsyncClient:
1822
1925
  await _release_response(response)
1823
1926
 
1824
1927
  async def get_instance_info(self, model_name: str, model_uid: str):
1928
+ await self._ensure_initialized()
1825
1929
  url = f"{self.base_url}/v1/models/instances"
1826
1930
  response = await self.session.get(
1827
1931
  url,
@@ -1835,6 +1939,7 @@ class AsyncClient:
1835
1939
  return response_data
1836
1940
 
1837
1941
  async def _get_supervisor_internal_address(self):
1942
+ await self._ensure_initialized()
1838
1943
  url = f"{self.base_url}/v1/address"
1839
1944
  response = await self.session.get(url, headers=self._headers)
1840
1945
  if response.status != 200:
@@ -1867,6 +1972,7 @@ class AsyncClient:
1867
1972
 
1868
1973
  """
1869
1974
 
1975
+ await self._ensure_initialized()
1870
1976
  url = f"{self.base_url}/v1/models/{model_uid}"
1871
1977
  response = await self.session.get(url, headers=self._headers)
1872
1978
  if response.status != 200:
@@ -1959,6 +2065,7 @@ class AsyncClient:
1959
2065
 
1960
2066
  """
1961
2067
 
2068
+ await self._ensure_initialized()
1962
2069
  url = f"{self.base_url}/v1/models/{model_uid}"
1963
2070
  response = await self.session.get(url, headers=self._headers)
1964
2071
  if response.status != 200:
@@ -1995,6 +2102,7 @@ class AsyncClient:
1995
2102
  RuntimeError
1996
2103
  Report failure to register the custom model. Provide details of failure through error message.
1997
2104
  """
2105
+ await self._ensure_initialized()
1998
2106
  url = f"{self.base_url}/v1/model_registrations/{model_type}"
1999
2107
  request_body = {"model": model, "worker_ip": worker_ip, "persist": persist}
2000
2108
  response = await self.session.post(
@@ -2025,6 +2133,7 @@ class AsyncClient:
2025
2133
  RuntimeError
2026
2134
  Report failure to unregister the custom model. Provide details of failure through error message.
2027
2135
  """
2136
+ await self._ensure_initialized()
2028
2137
  url = f"{self.base_url}/v1/model_registrations/{model_type}/{model_name}"
2029
2138
  response = await self.session.delete(url, headers=self._headers)
2030
2139
  if response.status != 200:
@@ -2056,6 +2165,7 @@ class AsyncClient:
2056
2165
  Report failure to list model registration. Provide details of failure through error message.
2057
2166
 
2058
2167
  """
2168
+ await self._ensure_initialized()
2059
2169
  url = f"{self.base_url}/v1/model_registrations/{model_type}"
2060
2170
  response = await self.session.get(url, headers=self._headers)
2061
2171
  if response.status != 200:
@@ -2090,6 +2200,7 @@ class AsyncClient:
2090
2200
  Raised when the request fails, including the reason for the failure.
2091
2201
  """
2092
2202
 
2203
+ await self._ensure_initialized()
2093
2204
  url = f"{self.base_url}/v1/cache/models"
2094
2205
  params = {
2095
2206
  "model_name": model_name,
@@ -2122,6 +2233,7 @@ class AsyncClient:
2122
2233
  Dict[str, Dict[str,str]]]
2123
2234
  Dictionary with keys "model_name" and values model_file_location.
2124
2235
  """
2236
+ await self._ensure_initialized()
2125
2237
  url = f"{self.base_url}/v1/cache/models/files"
2126
2238
  params = {
2127
2239
  "model_version": model_version,
@@ -2154,6 +2266,7 @@ class AsyncClient:
2154
2266
  str
2155
2267
  The response of the server.
2156
2268
  """
2269
+ await self._ensure_initialized()
2157
2270
  url = f"{self.base_url}/v1/cache/models"
2158
2271
  params = {
2159
2272
  "model_version": model_version,
@@ -2188,6 +2301,7 @@ class AsyncClient:
2188
2301
  List[Dict[str, Any]]
2189
2302
  The collection of registered models on the server.
2190
2303
  """
2304
+ await self._ensure_initialized()
2191
2305
  url = f"{self.base_url}/v1/model_registrations/{model_type}/{model_name}"
2192
2306
  response = await self.session.get(url, headers=self._headers)
2193
2307
  if response.status != 200:
@@ -2219,6 +2333,7 @@ class AsyncClient:
2219
2333
  Dict[str, List[Dict[str, Any]]]
2220
2334
  The supported engine parameters of registered models on the server.
2221
2335
  """
2336
+ await self._ensure_initialized()
2222
2337
  if not model_type:
2223
2338
  url = f"{self.base_url}/v1/engines/{model_name}"
2224
2339
  else:
@@ -2258,6 +2373,7 @@ class AsyncClient:
2258
2373
  Dict
2259
2374
  Return empty dict.
2260
2375
  """
2376
+ await self._ensure_initialized()
2261
2377
  url = f"{self.base_url}/v1/models/{model_uid}/requests/{request_id}/abort"
2262
2378
  response = await self.session.post(
2263
2379
  url, headers=self._headers, json={"block_duration": block_duration}
@@ -2272,6 +2388,7 @@ class AsyncClient:
2272
2388
  return response_data
2273
2389
 
2274
2390
  async def get_workers_info(self):
2391
+ await self._ensure_initialized()
2275
2392
  url = f"{self.base_url}/v1/workers"
2276
2393
  response = await self.session.get(url, headers=self._headers)
2277
2394
  if response.status != 200:
@@ -2289,6 +2406,7 @@ class AsyncClient:
2289
2406
  request_id: Optional[str] = None,
2290
2407
  ) -> Dict[str, Any]:
2291
2408
  """Relaunch a Worker and return its asynchronous operation status."""
2409
+ await self._ensure_initialized()
2292
2410
  response = await self.session.post(
2293
2411
  f"{self.base_url}/v1/workers/{quote(worker_address, safe='')}/relaunch",
2294
2412
  json={"python_executable": python_executable, "request_id": request_id},
@@ -2303,6 +2421,7 @@ class AsyncClient:
2303
2421
  return result
2304
2422
 
2305
2423
  async def get_worker_relaunch(self, operation_id: str) -> Dict[str, Any]:
2424
+ await self._ensure_initialized()
2306
2425
  response = await self.session.get(
2307
2426
  f"{self.base_url}/v1/worker-relaunches/{quote(operation_id, safe='')}",
2308
2427
  headers=self._headers,
@@ -2316,6 +2435,7 @@ class AsyncClient:
2316
2435
  return result
2317
2436
 
2318
2437
  async def list_worker_relaunches(self) -> List[Dict[str, Any]]:
2438
+ await self._ensure_initialized()
2319
2439
  response = await self.session.get(
2320
2440
  f"{self.base_url}/v1/worker-relaunches", headers=self._headers
2321
2441
  )
@@ -2328,6 +2448,7 @@ class AsyncClient:
2328
2448
  return result
2329
2449
 
2330
2450
  async def get_supervisor_info(self):
2451
+ await self._ensure_initialized()
2331
2452
  url = f"{self.base_url}/v1/supervisor"
2332
2453
  response = await self.session.get(url, headers=self._headers)
2333
2454
  if response.status != 200:
@@ -2339,6 +2460,7 @@ class AsyncClient:
2339
2460
  return response_json
2340
2461
 
2341
2462
  async def get_progress(self, request_id: str):
2463
+ await self._ensure_initialized()
2342
2464
  url = f"{self.base_url}/v1/requests/{request_id}/progress"
2343
2465
  response = await self.session.get(url, headers=self._headers)
2344
2466
  if response.status != 200:
@@ -2350,6 +2472,7 @@ class AsyncClient:
2350
2472
  return response_json
2351
2473
 
2352
2474
  async def abort_cluster(self):
2475
+ await self._ensure_initialized()
2353
2476
  url = f"{self.base_url}/v1/clusters"
2354
2477
  response = await self.session.delete(url, headers=self._headers)
2355
2478
  if response.status != 200:
@@ -18,8 +18,11 @@ from urllib.parse import quote
18
18
  import requests
19
19
 
20
20
  from ..common import (
21
+ IMAGE_DOWNLOAD_TIMEOUT,
21
22
  convert_float_to_int_or_str,
22
23
  encode_world_reference,
24
+ is_http_url,
25
+ normalize_endpoint,
23
26
  streaming_response_iterator,
24
27
  )
25
28
 
@@ -50,6 +53,20 @@ def _get_error_string(response: requests.Response) -> str:
50
53
  return "Unknown error"
51
54
 
52
55
 
56
+ def _streaming_response(response: requests.Response) -> Iterator[Any]:
57
+ def iterate():
58
+ try:
59
+ # Enter the cleanup scope before returning an unconsumed stream.
60
+ yield None
61
+ yield from streaming_response_iterator(response.iter_lines())
62
+ finally:
63
+ response.close()
64
+
65
+ stream = iterate()
66
+ next(stream)
67
+ return stream
68
+
69
+
53
70
  class RESTfulModelHandle:
54
71
  """
55
72
  A sync model interface (for RESTful client) which provides type hints that makes it much easier to use xinference
@@ -216,7 +233,7 @@ class RESTfulRerankModelHandle(RESTfulModelHandle):
216
233
  response = self.session.post(url, json=request_body, headers=self.auth_headers)
217
234
  if response.status_code != 200:
218
235
  raise RuntimeError(
219
- f"Failed to rerank documents, detail: {response.json()['detail']}"
236
+ f"Failed to rerank documents, detail: {_get_error_string(response)}"
220
237
  )
221
238
  response_data = response.json()
222
239
  return response_data
@@ -348,6 +365,20 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
348
365
  response_data = response.json()
349
366
  return response_data
350
367
 
368
+ def _download_if_url(self, image: Any) -> Any:
369
+ """Download an http(s) URL; paths, bytes and file objects pass through."""
370
+ if not (isinstance(image, str) and is_http_url(image)):
371
+ return image
372
+ # No auth headers: the Xinference credentials must not reach the image host.
373
+ try:
374
+ response = self.session.get(image, timeout=IMAGE_DOWNLOAD_TIMEOUT)
375
+ response.raise_for_status()
376
+ return response.content
377
+ except requests.RequestException as error:
378
+ raise RuntimeError(
379
+ f"Failed to download an image for editing, detail: {error}"
380
+ ) from error
381
+
351
382
  def image_edit(
352
383
  self,
353
384
  images: Union[Union[str, bytes], List[Union[str, bytes]]],
@@ -408,6 +439,12 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
408
439
  )
409
440
  """
410
441
  url = f"{self._base_url}/v1/images/edits"
442
+ # The route takes uploaded files only, so URLs are downloaded here.
443
+ if isinstance(images, list):
444
+ images = [self._download_if_url(image) for image in images]
445
+ else:
446
+ images = self._download_if_url(images)
447
+ mask = self._download_if_url(mask)
411
448
  params = {
412
449
  "model": self._model_uid,
413
450
  "prompt": prompt,
@@ -817,7 +854,7 @@ class RESTfulGenerateModelHandle(RESTfulModelHandle):
817
854
  )
818
855
 
819
856
  if stream:
820
- return streaming_response_iterator(response.iter_lines())
857
+ return _streaming_response(response)
821
858
 
822
859
  response_data = response.json()
823
860
  return response_data
@@ -898,7 +935,7 @@ class RESTfulChatModelHandle(RESTfulGenerateModelHandle):
898
935
  )
899
936
 
900
937
  if stream:
901
- return streaming_response_iterator(response.iter_lines())
938
+ return _streaming_response(response)
902
939
 
903
940
  response_data = response.json()
904
941
  return response_data
@@ -1170,7 +1207,7 @@ class RESTfulFlexibleModelHandle(RESTfulModelHandle):
1170
1207
 
1171
1208
  class Client:
1172
1209
  def __init__(self, base_url, api_key: Optional[str] = None):
1173
- self.base_url = base_url
1210
+ self.base_url = normalize_endpoint(base_url)
1174
1211
  self._headers: Dict[str, str] = {}
1175
1212
  self._cluster_authed = False
1176
1213
  self.session = requests.Session()
@@ -1221,7 +1258,7 @@ class Client:
1221
1258
  response = self.session.get(url, headers=self._headers)
1222
1259
  if response.status_code != 200:
1223
1260
  raise RuntimeError(
1224
- f"Failed to fetch VLLM models. detail: {response.json()['detail']}"
1261
+ f"Failed to fetch VLLM models. detail: {_get_error_string(response)}"
1225
1262
  )
1226
1263
 
1227
1264
  try:
@@ -1238,7 +1275,9 @@ class Client:
1238
1275
 
1239
1276
  response = self.session.post(url, json=payload)
1240
1277
  if response.status_code != 200:
1241
- raise RuntimeError(f"Failed to login, detail: {response.json()['detail']}")
1278
+ raise RuntimeError(
1279
+ f"Failed to login, detail: {_get_error_string(response)}"
1280
+ )
1242
1281
 
1243
1282
  response_data = response.json()
1244
1283
  # Only bearer token for now
@@ -1455,7 +1494,8 @@ class Client:
1455
1494
  ) -> Dict[str, Any]:
1456
1495
  """Start an asynchronous parameter reload with the same model UID.
1457
1496
 
1458
- Engine changes require launch-time ``enable_weight_cache=True``;
1497
+ Engine changes require weight retention enabled at launch (automatic
1498
+ on supported configurations, or ``enable_weight_cache=True``);
1459
1499
  a standalone ``reasoning_content`` update does not. Use
1460
1500
  ``get_model_reload_status`` to wait for ready/error after HTTP 202.
1461
1501
  """
@@ -1474,6 +1514,16 @@ class Client:
1474
1514
  )
1475
1515
  return response.json()
1476
1516
 
1517
+ def get_model_runtime_info(self, model_uid: str) -> Dict[str, Any]:
1518
+ """Return runtime_context_length (tokens, or None) and per-replica limits."""
1519
+ url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/runtime"
1520
+ response = self.session.get(url, headers=self._headers)
1521
+ if response.status_code != 200:
1522
+ raise RuntimeError(
1523
+ f"Failed to get model runtime info, detail: {_get_error_string(response)}"
1524
+ )
1525
+ return response.json()
1526
+
1477
1527
  def get_model_reload_status(self, model_uid: str) -> Dict[str, Any]:
1478
1528
  """Return the latest reload operation, including its stage and error."""
1479
1529
  url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/reload"
@@ -2082,15 +2132,42 @@ class Client:
2082
2132
  response_data = response.json()
2083
2133
  return response_data
2084
2134
 
2135
+ def check_component_update(
2136
+ self, component: str, worker_address: Optional[str] = None
2137
+ ) -> Dict[str, Any]:
2138
+ """Check the package source on the selected component's machine."""
2139
+ if component not in {"api", "supervisor", "worker"}:
2140
+ raise ValueError("Unknown component")
2141
+ if component == "worker":
2142
+ if not worker_address:
2143
+ raise ValueError("worker_address is required")
2144
+ path = f"workers/{quote(worker_address, safe='')}"
2145
+ else:
2146
+ path = component
2147
+ response = self.session.get(
2148
+ f"{self.base_url}/v1/{path}/updates", headers=self._headers
2149
+ )
2150
+ if response.status_code != 200:
2151
+ raise RuntimeError(
2152
+ f"Failed to check updates: {_get_error_string(response)}"
2153
+ )
2154
+ return response.json()
2155
+
2085
2156
  def relaunch_api(
2086
2157
  self,
2087
2158
  python_executable: Optional[str] = None,
2088
2159
  request_id: Optional[str] = None,
2160
+ *,
2161
+ version: Optional[str] = None,
2089
2162
  ) -> Dict[str, Any]:
2090
2163
  """Replace the distributed API process while existing requests drain."""
2091
2164
  response = self.session.post(
2092
2165
  f"{self.base_url}/v1/api/relaunch",
2093
- json={"python_executable": python_executable, "request_id": request_id},
2166
+ json={
2167
+ "python_executable": python_executable,
2168
+ "request_id": request_id,
2169
+ **({"version": version} if version is not None else {}),
2170
+ },
2094
2171
  headers=self._headers,
2095
2172
  )
2096
2173
  if response.status_code != 202:
@@ -2122,11 +2199,17 @@ class Client:
2122
2199
  self,
2123
2200
  python_executable: Optional[str] = None,
2124
2201
  request_id: Optional[str] = None,
2202
+ *,
2203
+ version: Optional[str] = None,
2125
2204
  ) -> Dict[str, Any]:
2126
2205
  """Replace the distributed Supervisor process while models remain running."""
2127
2206
  response = self.session.post(
2128
2207
  f"{self.base_url}/v1/supervisor/relaunch",
2129
- json={"python_executable": python_executable, "request_id": request_id},
2208
+ json={
2209
+ "python_executable": python_executable,
2210
+ "request_id": request_id,
2211
+ **({"version": version} if version is not None else {}),
2212
+ },
2130
2213
  headers=self._headers,
2131
2214
  )
2132
2215
  if response.status_code != 202:
@@ -2161,11 +2244,17 @@ class Client:
2161
2244
  worker_address: str,
2162
2245
  python_executable: Optional[str] = None,
2163
2246
  request_id: Optional[str] = None,
2247
+ *,
2248
+ version: Optional[str] = None,
2164
2249
  ) -> Dict[str, Any]:
2165
2250
  """Relaunch a Worker and return its asynchronous operation status."""
2166
2251
  response = self.session.post(
2167
2252
  f"{self.base_url}/v1/workers/{quote(worker_address, safe='')}/relaunch",
2168
- json={"python_executable": python_executable, "request_id": request_id},
2253
+ json={
2254
+ "python_executable": python_executable,
2255
+ "request_id": request_id,
2256
+ **({"version": version} if version is not None else {}),
2257
+ },
2169
2258
  headers=self._headers,
2170
2259
  )
2171
2260
  if response.status_code != 202:
@@ -18,9 +18,11 @@ from typing_extensions import Literal, NotRequired, TypedDict
18
18
 
19
19
  from ._compat import (
20
20
  BaseModel,
21
+ Field,
21
22
  create_model,
22
23
  create_model_from_typeddict,
23
24
  validate_arguments,
25
+ validator,
24
26
  )
25
27
  from .fields import (
26
28
  echo_field,
@@ -35,6 +37,11 @@ from .fields import (
35
37
  top_k_field,
36
38
  top_p_field,
37
39
  )
40
+ from .request_priority import (
41
+ MAX_REQUEST_PRIORITY,
42
+ MIN_REQUEST_PRIORITY,
43
+ validate_request_priority,
44
+ )
38
45
 
39
46
 
40
47
  class Image(TypedDict):
@@ -329,6 +336,7 @@ class LogitsProcessorList(List[LogitsProcessor]):
329
336
 
330
337
 
331
338
  class PytorchGenerateConfig(TypedDict, total=False):
339
+ priority: int
332
340
  cache_salt: Optional[str]
333
341
  temperature: float
334
342
  repetition_penalty: float
@@ -442,6 +450,12 @@ class ModelAndMessages(BaseModel):
442
450
 
443
451
 
444
452
  class CreateCompletionTorch(BaseModel):
453
+ priority: int = Field(default=0, ge=MIN_REQUEST_PRIORITY, le=MAX_REQUEST_PRIORITY)
454
+
455
+ _validate_priority = validator("priority", pre=True, allow_reuse=True)(
456
+ validate_request_priority
457
+ )
458
+
445
459
  echo: bool = echo_field
446
460
  ignore_eos: bool = False
447
461
  max_tokens: Optional[int] = max_tokens_field
@@ -495,6 +509,9 @@ class CreateChatCompletion( # type: ignore
495
509
  ):
496
510
  cache_salt: Optional[str] = None
497
511
  mm_processor_kwargs: Optional[Dict[str, Any]] = None
512
+ # Validate model-specific values before generation, without coercing numbers or booleans.
513
+ reasoning_effort: Optional[Any] = None
514
+ thinking_budget: Optional[Any] = None
498
515
 
499
516
 
500
517
  class LoRA:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xinference-client
3
- Version: 4.1.0
3
+ Version: 4.2.0
4
4
  Summary: Client for Xinference
5
5
  Home-page: https://github.com/xorbitsai/inference-client
6
6
  Author: Qin Xuye