xinference-client 4.1.0__tar.gz → 4.3.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.3.0}/PKG-INFO +1 -1
  2. {xinference_client-4.1.0 → xinference_client-4.3.0}/tests/test_async_client.py +5 -5
  3. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client/_compat.py +18 -3
  4. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client/_version.py +3 -3
  5. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client/client/common.py +35 -2
  6. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client/client/restful/async_restful_client.py +183 -45
  7. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client/client/restful/restful_client.py +163 -55
  8. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client/types.py +17 -0
  9. {xinference_client-4.1.0 → xinference_client-4.3.0/xinference_client.egg-info}/PKG-INFO +1 -1
  10. {xinference_client-4.1.0 → xinference_client-4.3.0}/LICENSE +0 -0
  11. {xinference_client-4.1.0 → xinference_client-4.3.0}/MANIFEST.in +0 -0
  12. {xinference_client-4.1.0 → xinference_client-4.3.0}/README.md +0 -0
  13. {xinference_client-4.1.0 → xinference_client-4.3.0}/pyproject.toml +0 -0
  14. {xinference_client-4.1.0 → xinference_client-4.3.0}/setup.cfg +0 -0
  15. {xinference_client-4.1.0 → xinference_client-4.3.0}/setup.py +0 -0
  16. {xinference_client-4.1.0 → xinference_client-4.3.0}/tests/test_async_client_cleanup.py +0 -0
  17. {xinference_client-4.1.0 → xinference_client-4.3.0}/third_party/inference/xinference/thirdparty/matcha/utils/monotonic_align/core.pyx +0 -0
  18. {xinference_client-4.1.0 → xinference_client-4.3.0}/versioneer.py +0 -0
  19. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client/__init__.py +0 -0
  20. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client/client/__init__.py +0 -0
  21. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client/client/restful/__init__.py +0 -0
  22. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client/fields.py +0 -0
  23. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client.egg-info/SOURCES.txt +0 -0
  24. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client.egg-info/dependency_links.txt +0 -0
  25. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client.egg-info/not-zip-safe +0 -0
  26. {xinference_client-4.1.0 → xinference_client-4.3.0}/xinference_client.egg-info/requires.txt +0 -0
  27. {xinference_client-4.1.0 → xinference_client-4.3.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.3.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()
@@ -11,6 +11,7 @@
11
11
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
+ import sys
14
15
  from typing import Dict, Iterable, List, Literal, Optional, Union
15
16
 
16
17
  from pydantic.version import VERSION as PYDANTIC_VERSION
@@ -23,6 +24,7 @@ if PYDANTIC_V2:
23
24
  BaseModel,
24
25
  Field,
25
26
  Protocol,
27
+ StrictInt,
26
28
  ValidationError,
27
29
  create_model,
28
30
  create_model_from_namedtuple,
@@ -40,6 +42,7 @@ else:
40
42
  BaseModel,
41
43
  Field,
42
44
  Protocol,
45
+ StrictInt,
43
46
  ValidationError,
44
47
  create_model,
45
48
  create_model_from_namedtuple,
@@ -65,11 +68,23 @@ from openai.types.shared_params.response_format_json_object import (
65
68
  )
66
69
  from openai.types.shared_params.response_format_text import ResponseFormatText
67
70
 
68
- OpenAIChatCompletionStreamOptionsParam = create_model_from_typeddict(
71
+
72
+ def _create_model_from_openai_typeddict(typeddict_cls):
73
+ model = create_model_from_typeddict(typeddict_cls)
74
+ # Python 3.14 defers annotation evaluation (PEP 649), so pydantic v1 leaves
75
+ # the TypedDict fields as unresolved ForwardRefs; resolve them in the
76
+ # namespace of the module that defines the TypedDict.
77
+ model.update_forward_refs(**vars(sys.modules[typeddict_cls.__module__]))
78
+ return model
79
+
80
+
81
+ OpenAIChatCompletionStreamOptionsParam = _create_model_from_openai_typeddict(
69
82
  ChatCompletionStreamOptionsParam
70
83
  )
71
- OpenAIChatCompletionToolParam = create_model_from_typeddict(ChatCompletionToolParam)
72
- OpenAIChatCompletionNamedToolChoiceParam = create_model_from_typeddict(
84
+ OpenAIChatCompletionToolParam = _create_model_from_openai_typeddict(
85
+ ChatCompletionToolParam
86
+ )
87
+ OpenAIChatCompletionNamedToolChoiceParam = _create_model_from_openai_typeddict(
73
88
  ChatCompletionNamedToolChoiceParam
74
89
  )
75
90
  from openai._types import Body
@@ -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-26T16:25:20+0800",
12
12
  "dirty": false,
13
13
  "error": null,
14
- "full-revisionid": "63f5e9dd6df9f0bc9a91569268e7528883255b2f",
15
- "version": "4.1.0"
14
+ "full-revisionid": "0fd4fc33a816d81f822532363a2517c0f9b2141c",
15
+ "version": "4.3.0"
16
16
  }
17
17
  ''' # END VERSION_JSON
18
18
 
@@ -17,6 +17,26 @@ 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
+
32
+
33
+ def read_file_input(value: Union[str, bytes]) -> bytes:
34
+ """Return the bytes of an upload given as a local file path or as bytes."""
35
+ if isinstance(value, str):
36
+ with open(value, "rb") as f:
37
+ return f.read()
38
+ return value
39
+
20
40
 
21
41
  def encode_world_reference(reference: Union[str, bytes], media_type: str) -> str:
22
42
  if isinstance(reference, str) and not os.path.isfile(reference):
@@ -66,12 +86,16 @@ def streaming_response_iterator(
66
86
 
67
87
  """
68
88
 
89
+ first_line = True
69
90
  for line in response_lines:
91
+ if first_line:
92
+ line = line.removeprefix(b"\xef\xbb\xbf")
93
+ first_line = False
70
94
  line = line.strip()
71
95
  if line.startswith(b"data:"):
72
96
  json_str = line[len(b"data:") :].strip()
73
97
  if json_str == b"[DONE]":
74
- continue
98
+ break
75
99
  data = json.loads(json_str.decode("utf-8"))
76
100
  error = data.get("error", None)
77
101
  if error is not None:
@@ -81,6 +105,8 @@ def streaming_response_iterator(
81
105
 
82
106
  async def async_streaming_response_iterator(
83
107
  response_or_lines: Any,
108
+ *,
109
+ _prime: bool = False,
84
110
  ) -> AsyncIterator[Any]:
85
111
  """
86
112
  Create an AsyncIterator to handle the streaming type of generation.
@@ -110,12 +136,19 @@ async def async_streaming_response_iterator(
110
136
  )
111
137
  response_lines = response.content if response is not None else response_or_lines
112
138
  try:
139
+ if _prime:
140
+ # Enter the cleanup scope before handing the stream to the caller.
141
+ yield None
142
+ first_line = True
113
143
  async for line in response_lines:
144
+ if first_line:
145
+ line = line.removeprefix(b"\xef\xbb\xbf")
146
+ first_line = False
114
147
  line = line.strip()
115
148
  if line.startswith(b"data:"):
116
149
  json_str = line[len(b"data:") :].strip()
117
150
  if json_str == b"[DONE]":
118
- continue
151
+ break
119
152
  data = json.loads(json_str.decode("utf-8"))
120
153
  error = data.get("error", None)
121
154
  if error is not None:
@@ -19,9 +19,13 @@ 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,
28
+ read_file_input,
25
29
  )
26
30
 
27
31
  if TYPE_CHECKING:
@@ -71,6 +75,12 @@ async def _release_response(response: aiohttp.ClientResponse):
71
75
  await response.wait_for_close()
72
76
 
73
77
 
78
+ async def _streaming_response(response: aiohttp.ClientResponse) -> AsyncIterator[Any]:
79
+ stream = async_streaming_response_iterator(response, _prime=True)
80
+ await anext(stream)
81
+ return stream
82
+
83
+
74
84
  def _schedule_session_close(client: Any) -> None:
75
85
  if not getattr(client, "session", None):
76
86
  return
@@ -362,6 +372,10 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
362
372
  :param image:
363
373
  """
364
374
  url = f"{self._base_url}/v1/images/variations"
375
+ if isinstance(image, list):
376
+ image = [await self._read_image(img) for img in image]
377
+ else:
378
+ image = await self._read_image(image)
365
379
  params = {
366
380
  "model": self._model_uid,
367
381
  "prompt": prompt,
@@ -416,6 +430,37 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
416
430
  await _release_response(response)
417
431
  return response_data
418
432
 
433
+ async def _download_if_url(self, image: Any) -> Any:
434
+ """Download an http(s) URL; paths, bytes and file objects pass through."""
435
+ if not (isinstance(image, str) and is_http_url(image)):
436
+ return image
437
+ # No auth headers: the Xinference credentials must not reach the image host.
438
+ # A request timeout replaces the session's, so carry its total over.
439
+ timeout = aiohttp.ClientTimeout(
440
+ total=self.session.timeout.total,
441
+ sock_connect=IMAGE_DOWNLOAD_TIMEOUT[0],
442
+ sock_read=IMAGE_DOWNLOAD_TIMEOUT[1],
443
+ )
444
+ try:
445
+ response = await self.session.get(image, timeout=timeout)
446
+ try:
447
+ response.raise_for_status()
448
+ return await response.read()
449
+ finally:
450
+ await _release_response(response)
451
+ except (aiohttp.ClientError, asyncio.TimeoutError) as error:
452
+ raise RuntimeError(
453
+ f"Failed to download an image, detail: {error}"
454
+ ) from error
455
+
456
+ async def _read_image(self, image: Any) -> Any:
457
+ """Return the upload content of an image URL, local file path or bytes."""
458
+ image = await self._download_if_url(image)
459
+ if isinstance(image, str):
460
+ with open(image, "rb") as f:
461
+ return f.read()
462
+ return image
463
+
419
464
  async def image_edit(
420
465
  self,
421
466
  images: Union[Union[str, bytes], List[Union[str, bytes]]],
@@ -476,6 +521,12 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
476
521
  )
477
522
  """
478
523
  url = f"{self._base_url}/v1/images/edits"
524
+ # The route takes uploaded files only, so URLs are downloaded here.
525
+ if isinstance(images, list):
526
+ images = [await self._download_if_url(image) for image in images]
527
+ else:
528
+ images = await self._download_if_url(images)
529
+ mask = await self._download_if_url(mask)
479
530
  params = {
480
531
  "model": self._model_uid,
481
532
  "prompt": prompt,
@@ -617,6 +668,8 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
617
668
  :param image:
618
669
  """
619
670
  url = f"{self._base_url}/v1/images/inpainting"
671
+ image = await self._read_image(image)
672
+ mask_image = await self._read_image(mask_image)
620
673
  params = {
621
674
  "model": self._model_uid,
622
675
  "prompt": prompt,
@@ -651,6 +704,7 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
651
704
 
652
705
  async def ocr(self, image: Union[str, bytes], **kwargs):
653
706
  url = f"{self._base_url}/v1/images/ocr"
707
+ image = await self._read_image(image)
654
708
  # aiohttp does not understand requests-style (key, (filename, value))
655
709
  # tuples; build a proper multipart form instead.
656
710
  form = aiohttp.FormData()
@@ -725,7 +779,7 @@ class AsyncRESTfulVideoModelHandle(AsyncRESTfulModelHandle):
725
779
  Parameters
726
780
  ----------
727
781
  image: `Union[str, bytes]`
728
- The input image to condition the generation on.
782
+ The input image to condition the generation on, as a local file path or bytes.
729
783
  prompt: `str` or `List[str]`
730
784
  The prompt or prompts to guide video generation. If not defined, you need to pass `prompt_embeds`.
731
785
  negative_prompt (`str` or `List[str]`, *optional*):
@@ -752,14 +806,13 @@ class AsyncRESTfulVideoModelHandle(AsyncRESTfulModelHandle):
752
806
  for key, value in params.items():
753
807
  data.add_field(key, str(value))
754
808
  data.add_field(
755
- "image", image, filename="image", content_type="application/octet-stream"
809
+ "image",
810
+ read_file_input(image),
811
+ filename="image",
812
+ content_type="application/octet-stream",
756
813
  )
757
814
  if video is not None:
758
- if isinstance(video, str):
759
- with open(video, "rb") as f:
760
- video_data = f.read()
761
- else:
762
- video_data = video
815
+ video_data = read_file_input(video)
763
816
  data.add_field(
764
817
  "video",
765
818
  video_data,
@@ -791,9 +844,9 @@ class AsyncRESTfulVideoModelHandle(AsyncRESTfulModelHandle):
791
844
  Parameters
792
845
  ----------
793
846
  first_frame: `Union[str, bytes]`
794
- The first frame to condition the generation on.
847
+ The first frame to condition the generation on, as a local file path or bytes.
795
848
  last_frame: `Union[str, bytes]`
796
- The last frame to condition the generation on.
849
+ The last frame to condition the generation on, as a local file path or bytes.
797
850
  prompt: `str` or `List[str]`
798
851
  The prompt or prompts to guide video generation. If not defined, you need to pass `prompt_embeds`.
799
852
  negative_prompt (`str` or `List[str]`, *optional*):
@@ -819,13 +872,13 @@ class AsyncRESTfulVideoModelHandle(AsyncRESTfulModelHandle):
819
872
  data.add_field(key, str(value))
820
873
  data.add_field(
821
874
  "first_frame",
822
- first_frame,
875
+ read_file_input(first_frame),
823
876
  filename="image",
824
877
  content_type="application/octet-stream",
825
878
  )
826
879
  data.add_field(
827
880
  "last_frame",
828
- last_frame,
881
+ read_file_input(last_frame),
829
882
  filename="image",
830
883
  content_type="application/octet-stream",
831
884
  )
@@ -935,7 +988,7 @@ class AsyncRESTfulGenerateModelHandle(AsyncRESTfulModelHandle):
935
988
  )
936
989
 
937
990
  if stream:
938
- return async_streaming_response_iterator(response)
991
+ return await _streaming_response(response)
939
992
  response_data = await response.json()
940
993
  await _release_response(response)
941
994
  return response_data
@@ -1016,7 +1069,7 @@ class AsyncRESTfulChatModelHandle(AsyncRESTfulGenerateModelHandle):
1016
1069
  )
1017
1070
 
1018
1071
  if stream:
1019
- return async_streaming_response_iterator(response)
1072
+ return await _streaming_response(response)
1020
1073
 
1021
1074
  response_data = await response.json()
1022
1075
  await _release_response(response)
@@ -1318,29 +1371,37 @@ class AsyncRESTfulFlexibleModelHandle(AsyncRESTfulModelHandle):
1318
1371
 
1319
1372
  class AsyncClient:
1320
1373
  def __init__(self, base_url, api_key: Optional[str] = None):
1321
- self.base_url = base_url
1374
+ self.base_url = normalize_endpoint(base_url)
1375
+ self._api_key = api_key
1322
1376
  self._headers: Dict[str, str] = {}
1323
- self._cluster_authed = False
1377
+ # None until the first request has probed the cluster (_ensure_initialized).
1378
+ self._cluster_authed: Optional[bool] = None
1379
+ self._init_task: Optional["asyncio.Task[Optional[Exception]]"] = None
1324
1380
  self.timeout = aiohttp.ClientTimeout(total=1800)
1325
1381
  self._session_loop = asyncio.get_running_loop()
1326
1382
  self.session = aiohttp.ClientSession(
1327
1383
  connector=aiohttp.TCPConnector(force_close=True), timeout=self.timeout
1328
1384
  )
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
1385
 
1333
1386
  async def close(self):
1334
- """Close the AsyncClient session."""
1335
- if self.session:
1336
- await self.session.close()
1337
- self.session = None
1387
+ """Stop initialization and close the AsyncClient session."""
1388
+ init_task = getattr(self, "_init_task", None)
1389
+ try:
1390
+ if init_task is not None:
1391
+ if not init_task.done():
1392
+ init_task.cancel()
1393
+ await asyncio.gather(init_task, return_exceptions=True)
1394
+ finally:
1395
+ self._init_task = None
1396
+ if self.session:
1397
+ await self.session.close()
1398
+ self.session = None
1338
1399
 
1339
1400
  def __del__(self):
1340
1401
  _schedule_session_close(self)
1341
1402
 
1342
1403
  def _set_token(self, token: Optional[str]):
1343
- if not self._cluster_authed or token is None:
1404
+ if self._cluster_authed is False or token is None:
1344
1405
  return
1345
1406
  self._headers["Authorization"] = f"Bearer {token}"
1346
1407
 
@@ -1351,32 +1412,61 @@ class AsyncClient:
1351
1412
  else None
1352
1413
  )
1353
1414
 
1354
- def _check_cluster_authenticated(self):
1355
- import requests
1356
-
1357
- session = requests.Session()
1415
+ async def _check_cluster_authenticated(self) -> bool:
1358
1416
  url = f"{self.base_url}/v1/cluster/auth"
1359
- response = session.get(url)
1417
+ response = await self.session.get(url)
1360
1418
  # 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"])
1419
+ if response.status == 404:
1420
+ await _release_response(response)
1421
+ return False
1422
+ if response.status != 200:
1423
+ raise RuntimeError(
1424
+ f"Failed to get cluster information, detail: {await _get_error_string(response)}"
1425
+ )
1426
+ response_data = await response.json()
1427
+ await _release_response(response)
1428
+ return bool(response_data["auth"])
1429
+
1430
+ async def _ensure_initialized(self) -> None:
1431
+ """Probe the cluster before the first request, without blocking the loop.
1432
+
1433
+ Concurrent first requests await one probe task and get its result or its
1434
+ error. The task is shielded, so cancelling one request does not cancel the
1435
+ probe for the others. A failed probe is not remembered: the next request
1436
+ starts a new one.
1437
+ """
1438
+ if self._cluster_authed is not None:
1439
+ return
1440
+ if self._init_task is None or self._init_task.done():
1441
+ self._init_task = asyncio.create_task(self._initialize())
1442
+ error = await asyncio.shield(self._init_task)
1443
+ if error is not None:
1444
+ raise error
1445
+
1446
+ async def _initialize(self) -> Optional[Exception]:
1447
+ # Returns the probe's error instead of raising it: if every caller was
1448
+ # cancelled, nobody would retrieve a raised one and asyncio logs that.
1449
+ # The result is stored only after the probe and the API key were handled.
1450
+ try:
1451
+ authed = await self._check_cluster_authenticated()
1452
+ if not authed:
1453
+ # A token set before the probe only applies to an auth cluster.
1454
+ self._headers.pop("Authorization", None)
1455
+ elif self._api_key is not None:
1456
+ # A token set before the probe is newer than the API key.
1457
+ self._headers.setdefault("Authorization", f"Bearer {self._api_key}")
1458
+ self._cluster_authed = authed
1459
+ return None
1460
+ except Exception as error:
1461
+ return error
1371
1462
 
1372
1463
  async def vllm_models(self) -> Dict[str, Any]:
1464
+ await self._ensure_initialized()
1373
1465
  url = f"{self.base_url}/v1/models/vllm-supported"
1374
1466
  response = await self.session.get(url, headers=self._headers)
1375
1467
  if response.status != 200:
1376
- response_data = await response.json()
1377
- await _release_response(response)
1378
1468
  raise RuntimeError(
1379
- f"Failed to get cluster information, detail: {response_data['detail']}"
1469
+ f"Failed to get cluster information, detail: {await _get_error_string(response)}"
1380
1470
  )
1381
1471
 
1382
1472
  try:
@@ -1387,6 +1477,7 @@ class AsyncClient:
1387
1477
  raise RuntimeError(f"Error parsing JSON response: {e}")
1388
1478
 
1389
1479
  async def login(self, username: str, password: str):
1480
+ await self._ensure_initialized()
1390
1481
  if not self._cluster_authed:
1391
1482
  return
1392
1483
  url = f"{self.base_url}/token"
@@ -1395,10 +1486,8 @@ class AsyncClient:
1395
1486
 
1396
1487
  response = await self.session.post(url, json=payload)
1397
1488
  if response.status != 200:
1398
- response_data = await response.json()
1399
- await _release_response(response)
1400
1489
  raise RuntimeError(
1401
- f"Failed to get cluster information, detail: {response_data['detail']}"
1490
+ f"Failed to get cluster information, detail: {await _get_error_string(response)}"
1402
1491
  )
1403
1492
 
1404
1493
  response_data = await response.json()
@@ -1418,6 +1507,7 @@ class AsyncClient:
1418
1507
 
1419
1508
  """
1420
1509
 
1510
+ await self._ensure_initialized()
1421
1511
  url = f"{self.base_url}/v1/models"
1422
1512
 
1423
1513
  response = await self.session.get(url, headers=self._headers)
@@ -1523,6 +1613,7 @@ class AsyncClient:
1523
1613
 
1524
1614
  """
1525
1615
 
1616
+ await self._ensure_initialized()
1526
1617
  url = f"{self.base_url}/v1/models"
1527
1618
 
1528
1619
  # convert float to int or string since the RESTful API does not accept float.
@@ -1574,6 +1665,7 @@ class AsyncClient:
1574
1665
  return response_data["model_uid"]
1575
1666
 
1576
1667
  async def get_autostart_config(self) -> Dict:
1668
+ await self._ensure_initialized()
1577
1669
  url = f"{self.base_url}/v1/autostart/models"
1578
1670
  response = await self.session.get(url, headers=self._headers)
1579
1671
  if response.status != 200:
@@ -1585,6 +1677,7 @@ class AsyncClient:
1585
1677
  return response_data
1586
1678
 
1587
1679
  async def get_autostart_model_summary(self) -> Dict:
1680
+ await self._ensure_initialized()
1588
1681
  url = f"{self.base_url}/v1/autostart/models/summary"
1589
1682
  response = await self.session.get(url, headers=self._headers)
1590
1683
  if response.status != 200:
@@ -1596,6 +1689,7 @@ class AsyncClient:
1596
1689
  return response_data
1597
1690
 
1598
1691
  async def upsert_autostart_model(self, entry: Dict) -> Dict:
1692
+ await self._ensure_initialized()
1599
1693
  url = f"{self.base_url}/v1/autostart/models"
1600
1694
  response = await self.session.post(url, json=entry, headers=self._headers)
1601
1695
  if response.status != 200:
@@ -1607,6 +1701,7 @@ class AsyncClient:
1607
1701
  return response_data
1608
1702
 
1609
1703
  async def remove_autostart_model(self, model_uid: str) -> Dict:
1704
+ await self._ensure_initialized()
1610
1705
  url = f"{self.base_url}/v1/autostart/models/{quote(model_uid, safe='')}"
1611
1706
  response = await self.session.delete(url, headers=self._headers)
1612
1707
  if response.status != 200:
@@ -1626,10 +1721,12 @@ class AsyncClient:
1626
1721
  ) -> Dict[str, Any]:
1627
1722
  """Start an asynchronous parameter reload with the same model UID.
1628
1723
 
1629
- Engine changes require launch-time ``enable_weight_cache=True``;
1724
+ Engine changes require weight retention enabled at launch (automatic
1725
+ on supported configurations, or ``enable_weight_cache=True``);
1630
1726
  a standalone ``reasoning_content`` update does not. Use
1631
1727
  ``get_model_reload_status`` to wait for ready/error after HTTP 202.
1632
1728
  """
1729
+ await self._ensure_initialized()
1633
1730
  url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/reload"
1634
1731
  payload = {"model_config": model_config, "drain_timeout": drain_timeout}
1635
1732
  if python_executable is not None:
@@ -1647,8 +1744,23 @@ class AsyncClient:
1647
1744
  await _release_response(response)
1648
1745
  return data
1649
1746
 
1747
+ async def get_model_runtime_info(self, model_uid: str) -> Dict[str, Any]:
1748
+ """Return runtime_context_length (tokens, or None) and per-replica limits."""
1749
+ await self._ensure_initialized()
1750
+ url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/runtime"
1751
+ response = await self.session.get(url, headers=self._headers)
1752
+ if response.status != 200:
1753
+ raise RuntimeError(
1754
+ f"Failed to get model runtime info, detail: {await _get_error_string(response)}"
1755
+ )
1756
+ try:
1757
+ return await response.json()
1758
+ finally:
1759
+ await _release_response(response)
1760
+
1650
1761
  async def get_model_reload_status(self, model_uid: str) -> Dict[str, Any]:
1651
1762
  """Return the latest reload operation, including its stage and error."""
1763
+ await self._ensure_initialized()
1652
1764
  url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/reload"
1653
1765
  response = await self.session.get(url, headers=self._headers)
1654
1766
  if response.status != 200:
@@ -1661,6 +1773,7 @@ class AsyncClient:
1661
1773
 
1662
1774
  async def get_model_reload_config(self, model_uid: str) -> Dict[str, Any]:
1663
1775
  """Return editable parameters, their types and current explicit values."""
1776
+ await self._ensure_initialized()
1664
1777
  url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/reload/config"
1665
1778
  response = await self.session.get(url, headers=self._headers)
1666
1779
  if response.status != 200:
@@ -1687,6 +1800,7 @@ class AsyncClient:
1687
1800
 
1688
1801
  """
1689
1802
 
1803
+ await self._ensure_initialized()
1690
1804
  url = f"{self.base_url}/v1/models/{model_uid}"
1691
1805
 
1692
1806
  response = await self.session.delete(url, headers=self._headers)
@@ -1734,6 +1848,7 @@ class AsyncClient:
1734
1848
  A single-replica result, or ``{"replica": int, "replicas": list}``
1735
1849
  when more than one replica is requested.
1736
1850
  """
1851
+ await self._ensure_initialized()
1737
1852
  url = f"{self.base_url}/v1/models/{model_uid}/replicas"
1738
1853
  payload: Dict[str, Any] = {}
1739
1854
  if replica_config is not None:
@@ -1756,6 +1871,7 @@ class AsyncClient:
1756
1871
  async def terminate_model_replica(self, model_uid: str, replica_id: int) -> int:
1757
1872
  """Terminate a specific replica of a running model."""
1758
1873
 
1874
+ await self._ensure_initialized()
1759
1875
  url = f"{self.base_url}/v1/models/{model_uid}/replicas/{replica_id}"
1760
1876
 
1761
1877
  response = await self.session.delete(url, headers=self._headers)
@@ -1787,6 +1903,7 @@ class AsyncClient:
1787
1903
  RuntimeError
1788
1904
  Report failure to get the wanted model with given model_uid. Provide details of failure through error message.
1789
1905
  """
1906
+ await self._ensure_initialized()
1790
1907
  url = f"{self.base_url}/v1/models/{model_uid}/progress"
1791
1908
 
1792
1909
  response = await self.session.get(url, headers=self._headers)
@@ -1812,6 +1929,7 @@ class AsyncClient:
1812
1929
  RuntimeError
1813
1930
  Report failure to get the wanted model with given model_uid. Provide details of failure through error message.
1814
1931
  """
1932
+ await self._ensure_initialized()
1815
1933
  url = f"{self.base_url}/v1/models/{model_uid}/cancel"
1816
1934
 
1817
1935
  response = await self.session.post(url, headers=self._headers)
@@ -1822,6 +1940,7 @@ class AsyncClient:
1822
1940
  await _release_response(response)
1823
1941
 
1824
1942
  async def get_instance_info(self, model_name: str, model_uid: str):
1943
+ await self._ensure_initialized()
1825
1944
  url = f"{self.base_url}/v1/models/instances"
1826
1945
  response = await self.session.get(
1827
1946
  url,
@@ -1835,6 +1954,7 @@ class AsyncClient:
1835
1954
  return response_data
1836
1955
 
1837
1956
  async def _get_supervisor_internal_address(self):
1957
+ await self._ensure_initialized()
1838
1958
  url = f"{self.base_url}/v1/address"
1839
1959
  response = await self.session.get(url, headers=self._headers)
1840
1960
  if response.status != 200:
@@ -1867,6 +1987,7 @@ class AsyncClient:
1867
1987
 
1868
1988
  """
1869
1989
 
1990
+ await self._ensure_initialized()
1870
1991
  url = f"{self.base_url}/v1/models/{model_uid}"
1871
1992
  response = await self.session.get(url, headers=self._headers)
1872
1993
  if response.status != 200:
@@ -1959,6 +2080,7 @@ class AsyncClient:
1959
2080
 
1960
2081
  """
1961
2082
 
2083
+ await self._ensure_initialized()
1962
2084
  url = f"{self.base_url}/v1/models/{model_uid}"
1963
2085
  response = await self.session.get(url, headers=self._headers)
1964
2086
  if response.status != 200:
@@ -1995,6 +2117,7 @@ class AsyncClient:
1995
2117
  RuntimeError
1996
2118
  Report failure to register the custom model. Provide details of failure through error message.
1997
2119
  """
2120
+ await self._ensure_initialized()
1998
2121
  url = f"{self.base_url}/v1/model_registrations/{model_type}"
1999
2122
  request_body = {"model": model, "worker_ip": worker_ip, "persist": persist}
2000
2123
  response = await self.session.post(
@@ -2025,6 +2148,7 @@ class AsyncClient:
2025
2148
  RuntimeError
2026
2149
  Report failure to unregister the custom model. Provide details of failure through error message.
2027
2150
  """
2151
+ await self._ensure_initialized()
2028
2152
  url = f"{self.base_url}/v1/model_registrations/{model_type}/{model_name}"
2029
2153
  response = await self.session.delete(url, headers=self._headers)
2030
2154
  if response.status != 200:
@@ -2056,6 +2180,7 @@ class AsyncClient:
2056
2180
  Report failure to list model registration. Provide details of failure through error message.
2057
2181
 
2058
2182
  """
2183
+ await self._ensure_initialized()
2059
2184
  url = f"{self.base_url}/v1/model_registrations/{model_type}"
2060
2185
  response = await self.session.get(url, headers=self._headers)
2061
2186
  if response.status != 200:
@@ -2090,6 +2215,7 @@ class AsyncClient:
2090
2215
  Raised when the request fails, including the reason for the failure.
2091
2216
  """
2092
2217
 
2218
+ await self._ensure_initialized()
2093
2219
  url = f"{self.base_url}/v1/cache/models"
2094
2220
  params = {
2095
2221
  "model_name": model_name,
@@ -2122,6 +2248,7 @@ class AsyncClient:
2122
2248
  Dict[str, Dict[str,str]]]
2123
2249
  Dictionary with keys "model_name" and values model_file_location.
2124
2250
  """
2251
+ await self._ensure_initialized()
2125
2252
  url = f"{self.base_url}/v1/cache/models/files"
2126
2253
  params = {
2127
2254
  "model_version": model_version,
@@ -2154,6 +2281,7 @@ class AsyncClient:
2154
2281
  str
2155
2282
  The response of the server.
2156
2283
  """
2284
+ await self._ensure_initialized()
2157
2285
  url = f"{self.base_url}/v1/cache/models"
2158
2286
  params = {
2159
2287
  "model_version": model_version,
@@ -2188,6 +2316,7 @@ class AsyncClient:
2188
2316
  List[Dict[str, Any]]
2189
2317
  The collection of registered models on the server.
2190
2318
  """
2319
+ await self._ensure_initialized()
2191
2320
  url = f"{self.base_url}/v1/model_registrations/{model_type}/{model_name}"
2192
2321
  response = await self.session.get(url, headers=self._headers)
2193
2322
  if response.status != 200:
@@ -2219,6 +2348,7 @@ class AsyncClient:
2219
2348
  Dict[str, List[Dict[str, Any]]]
2220
2349
  The supported engine parameters of registered models on the server.
2221
2350
  """
2351
+ await self._ensure_initialized()
2222
2352
  if not model_type:
2223
2353
  url = f"{self.base_url}/v1/engines/{model_name}"
2224
2354
  else:
@@ -2258,6 +2388,7 @@ class AsyncClient:
2258
2388
  Dict
2259
2389
  Return empty dict.
2260
2390
  """
2391
+ await self._ensure_initialized()
2261
2392
  url = f"{self.base_url}/v1/models/{model_uid}/requests/{request_id}/abort"
2262
2393
  response = await self.session.post(
2263
2394
  url, headers=self._headers, json={"block_duration": block_duration}
@@ -2272,6 +2403,7 @@ class AsyncClient:
2272
2403
  return response_data
2273
2404
 
2274
2405
  async def get_workers_info(self):
2406
+ await self._ensure_initialized()
2275
2407
  url = f"{self.base_url}/v1/workers"
2276
2408
  response = await self.session.get(url, headers=self._headers)
2277
2409
  if response.status != 200:
@@ -2289,6 +2421,7 @@ class AsyncClient:
2289
2421
  request_id: Optional[str] = None,
2290
2422
  ) -> Dict[str, Any]:
2291
2423
  """Relaunch a Worker and return its asynchronous operation status."""
2424
+ await self._ensure_initialized()
2292
2425
  response = await self.session.post(
2293
2426
  f"{self.base_url}/v1/workers/{quote(worker_address, safe='')}/relaunch",
2294
2427
  json={"python_executable": python_executable, "request_id": request_id},
@@ -2303,6 +2436,7 @@ class AsyncClient:
2303
2436
  return result
2304
2437
 
2305
2438
  async def get_worker_relaunch(self, operation_id: str) -> Dict[str, Any]:
2439
+ await self._ensure_initialized()
2306
2440
  response = await self.session.get(
2307
2441
  f"{self.base_url}/v1/worker-relaunches/{quote(operation_id, safe='')}",
2308
2442
  headers=self._headers,
@@ -2316,6 +2450,7 @@ class AsyncClient:
2316
2450
  return result
2317
2451
 
2318
2452
  async def list_worker_relaunches(self) -> List[Dict[str, Any]]:
2453
+ await self._ensure_initialized()
2319
2454
  response = await self.session.get(
2320
2455
  f"{self.base_url}/v1/worker-relaunches", headers=self._headers
2321
2456
  )
@@ -2328,6 +2463,7 @@ class AsyncClient:
2328
2463
  return result
2329
2464
 
2330
2465
  async def get_supervisor_info(self):
2466
+ await self._ensure_initialized()
2331
2467
  url = f"{self.base_url}/v1/supervisor"
2332
2468
  response = await self.session.get(url, headers=self._headers)
2333
2469
  if response.status != 200:
@@ -2339,6 +2475,7 @@ class AsyncClient:
2339
2475
  return response_json
2340
2476
 
2341
2477
  async def get_progress(self, request_id: str):
2478
+ await self._ensure_initialized()
2342
2479
  url = f"{self.base_url}/v1/requests/{request_id}/progress"
2343
2480
  response = await self.session.get(url, headers=self._headers)
2344
2481
  if response.status != 200:
@@ -2350,6 +2487,7 @@ class AsyncClient:
2350
2487
  return response_json
2351
2488
 
2352
2489
  async def abort_cluster(self):
2490
+ await self._ensure_initialized()
2353
2491
  url = f"{self.base_url}/v1/clusters"
2354
2492
  response = await self.session.delete(url, headers=self._headers)
2355
2493
  if response.status != 200:
@@ -18,8 +18,12 @@ 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,
26
+ read_file_input,
23
27
  streaming_response_iterator,
24
28
  )
25
29
 
@@ -50,6 +54,20 @@ def _get_error_string(response: requests.Response) -> str:
50
54
  return "Unknown error"
51
55
 
52
56
 
57
+ def _streaming_response(response: requests.Response) -> Iterator[Any]:
58
+ def iterate():
59
+ try:
60
+ # Enter the cleanup scope before returning an unconsumed stream.
61
+ yield None
62
+ yield from streaming_response_iterator(response.iter_lines())
63
+ finally:
64
+ response.close()
65
+
66
+ stream = iterate()
67
+ next(stream)
68
+ return stream
69
+
70
+
53
71
  class RESTfulModelHandle:
54
72
  """
55
73
  A sync model interface (for RESTful client) which provides type hints that makes it much easier to use xinference
@@ -216,7 +234,7 @@ class RESTfulRerankModelHandle(RESTfulModelHandle):
216
234
  response = self.session.post(url, json=request_body, headers=self.auth_headers)
217
235
  if response.status_code != 200:
218
236
  raise RuntimeError(
219
- f"Failed to rerank documents, detail: {response.json()['detail']}"
237
+ f"Failed to rerank documents, detail: {_get_error_string(response)}"
220
238
  )
221
239
  response_data = response.json()
222
240
  return response_data
@@ -309,6 +327,10 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
309
327
  :param image:
310
328
  """
311
329
  url = f"{self._base_url}/v1/images/variations"
330
+ if isinstance(image, list):
331
+ image = [self._read_image(img) for img in image]
332
+ else:
333
+ image = self._read_image(image)
312
334
  params = {
313
335
  "model": self._model_uid,
314
336
  "prompt": prompt,
@@ -348,6 +370,28 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
348
370
  response_data = response.json()
349
371
  return response_data
350
372
 
373
+ def _download_if_url(self, image: Any) -> Any:
374
+ """Download an http(s) URL; paths, bytes and file objects pass through."""
375
+ if not (isinstance(image, str) and is_http_url(image)):
376
+ return image
377
+ # No auth headers: the Xinference credentials must not reach the image host.
378
+ try:
379
+ response = self.session.get(image, timeout=IMAGE_DOWNLOAD_TIMEOUT)
380
+ response.raise_for_status()
381
+ return response.content
382
+ except requests.RequestException as error:
383
+ raise RuntimeError(
384
+ f"Failed to download an image, detail: {error}"
385
+ ) from error
386
+
387
+ def _read_image(self, image: Any) -> Any:
388
+ """Return the upload content of an image URL, local file path or bytes."""
389
+ image = self._download_if_url(image)
390
+ if isinstance(image, str):
391
+ with open(image, "rb") as f:
392
+ return f.read()
393
+ return image
394
+
351
395
  def image_edit(
352
396
  self,
353
397
  images: Union[Union[str, bytes], List[Union[str, bytes]]],
@@ -408,6 +452,12 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
408
452
  )
409
453
  """
410
454
  url = f"{self._base_url}/v1/images/edits"
455
+ # The route takes uploaded files only, so URLs are downloaded here.
456
+ if isinstance(images, list):
457
+ images = [self._download_if_url(image) for image in images]
458
+ else:
459
+ images = self._download_if_url(images)
460
+ mask = self._download_if_url(mask)
411
461
  params = {
412
462
  "model": self._model_uid,
413
463
  "prompt": prompt,
@@ -421,44 +471,49 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
421
471
  if value is not None:
422
472
  files.append((key, (None, value)))
423
473
 
424
- # Handle single image or multiple images using requests format
425
- if isinstance(images, list):
426
- # Validate image list is not empty
427
- if len(images) == 0:
428
- raise ValueError("Image list cannot be empty")
429
- # Multiple images - send as image[] array
430
- for i, img in enumerate(images):
431
- if isinstance(img, str):
474
+ try:
475
+ # Handle single image or multiple images using requests format
476
+ if isinstance(images, list):
477
+ # Validate image list is not empty
478
+ if len(images) == 0:
479
+ raise ValueError("Image list cannot be empty")
480
+ # Multiple images - send as image[] array
481
+ for i, img in enumerate(images):
482
+ if isinstance(img, str):
483
+ # File path - open file
484
+ f = open(img, "rb")
485
+ files.append(
486
+ (f"images[]", (f"image_{i}", f, "application/octet-stream"))
487
+ )
488
+ else:
489
+ # Binary data
490
+ files.append(
491
+ (
492
+ f"images[]",
493
+ (f"image_{i}", img, "application/octet-stream"),
494
+ )
495
+ )
496
+ else:
497
+ # Single image
498
+ if isinstance(images, str):
432
499
  # File path - open file
433
- f = open(img, "rb")
434
- files.append(
435
- (f"images[]", (f"image_{i}", f, "application/octet-stream"))
436
- )
500
+ f = open(images, "rb")
501
+ files.append(("images", ("image", f, "application/octet-stream")))
437
502
  else:
438
503
  # Binary data
439
504
  files.append(
440
- (f"images[]", (f"image_{i}", img, "application/octet-stream"))
505
+ ("images", ("image", images, "application/octet-stream"))
441
506
  )
442
- else:
443
- # Single image
444
- if isinstance(images, str):
445
- # File path - open file
446
- f = open(images, "rb")
447
- files.append(("images", ("image", f, "application/octet-stream")))
448
- else:
449
- # Binary data
450
- files.append(("images", ("image", images, "application/octet-stream")))
451
-
452
- if mask is not None:
453
- if isinstance(mask, str):
454
- # File path - open file
455
- f = open(mask, "rb")
456
- files.append(("mask", ("mask", f, "application/octet-stream")))
457
- else:
458
- # Binary data
459
- files.append(("mask", ("mask", mask, "application/octet-stream")))
460
507
 
461
- try:
508
+ if mask is not None:
509
+ if isinstance(mask, str):
510
+ # File path - open file
511
+ f = open(mask, "rb")
512
+ files.append(("mask", ("mask", f, "application/octet-stream")))
513
+ else:
514
+ # Binary data
515
+ files.append(("mask", ("mask", mask, "application/octet-stream")))
516
+
462
517
  response = self.session.post(url, files=files, headers=self.auth_headers)
463
518
  if response.status_code != 200:
464
519
  raise RuntimeError(
@@ -529,6 +584,8 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
529
584
  :param image:
530
585
  """
531
586
  url = f"{self._base_url}/v1/images/inpainting"
587
+ image = self._read_image(image)
588
+ mask_image = self._read_image(mask_image)
532
589
  params = {
533
590
  "model": self._model_uid,
534
591
  "prompt": prompt,
@@ -556,6 +613,7 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
556
613
 
557
614
  def ocr(self, image: Union[str, bytes], **kwargs):
558
615
  url = f"{self._base_url}/v1/images/ocr"
616
+ image = self._read_image(image)
559
617
  params = {
560
618
  "model": self._model_uid,
561
619
  "kwargs": json.dumps(kwargs),
@@ -626,7 +684,7 @@ class RESTfulVideoModelHandle(RESTfulModelHandle):
626
684
  Parameters
627
685
  ----------
628
686
  image: `Union[str, bytes]`
629
- The input image to condition the generation on.
687
+ The input image to condition the generation on, as a local file path or bytes.
630
688
  prompt: `str` or `List[str]`
631
689
  The prompt or prompts to guide video generation. If not defined, you need to pass `prompt_embeds`.
632
690
  negative_prompt (`str` or `List[str]`, *optional*):
@@ -651,13 +709,11 @@ class RESTfulVideoModelHandle(RESTfulModelHandle):
651
709
  files: List[Any] = []
652
710
  for key, value in params.items():
653
711
  files.append((key, (None, value)))
654
- files.append(("image", ("image", image, "application/octet-stream")))
712
+ files.append(
713
+ ("image", ("image", read_file_input(image), "application/octet-stream"))
714
+ )
655
715
  if video is not None:
656
- if isinstance(video, str):
657
- with open(video, "rb") as f:
658
- video_data = f.read()
659
- else:
660
- video_data = video
716
+ video_data = read_file_input(video)
661
717
  files.append(
662
718
  (
663
719
  "video",
@@ -688,9 +744,9 @@ class RESTfulVideoModelHandle(RESTfulModelHandle):
688
744
  Parameters
689
745
  ----------
690
746
  first_frame: `Union[str, bytes]`
691
- The first frame to condition the generation on.
747
+ The first frame to condition the generation on, as a local file path or bytes.
692
748
  last_frame: `Union[str, bytes]`
693
- The last frame to condition the generation on.
749
+ The last frame to condition the generation on, as a local file path or bytes.
694
750
  prompt: `str` or `List[str]`
695
751
  The prompt or prompts to guide video generation. If not defined, you need to pass `prompt_embeds`.
696
752
  negative_prompt (`str` or `List[str]`, *optional*):
@@ -713,10 +769,10 @@ class RESTfulVideoModelHandle(RESTfulModelHandle):
713
769
  files: List[Any] = []
714
770
  for key, value in params.items():
715
771
  files.append((key, (None, value)))
716
- files.append(
717
- ("first_frame", ("image", first_frame, "application/octet-stream"))
718
- )
719
- files.append(("last_frame", ("image", last_frame, "application/octet-stream")))
772
+ for key, frame in (("first_frame", first_frame), ("last_frame", last_frame)):
773
+ files.append(
774
+ (key, ("image", read_file_input(frame), "application/octet-stream"))
775
+ )
720
776
  response = self.session.post(url, files=files, headers=self.auth_headers)
721
777
  if response.status_code != 200:
722
778
  raise RuntimeError(
@@ -817,7 +873,7 @@ class RESTfulGenerateModelHandle(RESTfulModelHandle):
817
873
  )
818
874
 
819
875
  if stream:
820
- return streaming_response_iterator(response.iter_lines())
876
+ return _streaming_response(response)
821
877
 
822
878
  response_data = response.json()
823
879
  return response_data
@@ -898,7 +954,7 @@ class RESTfulChatModelHandle(RESTfulGenerateModelHandle):
898
954
  )
899
955
 
900
956
  if stream:
901
- return streaming_response_iterator(response.iter_lines())
957
+ return _streaming_response(response)
902
958
 
903
959
  response_data = response.json()
904
960
  return response_data
@@ -1170,7 +1226,7 @@ class RESTfulFlexibleModelHandle(RESTfulModelHandle):
1170
1226
 
1171
1227
  class Client:
1172
1228
  def __init__(self, base_url, api_key: Optional[str] = None):
1173
- self.base_url = base_url
1229
+ self.base_url = normalize_endpoint(base_url)
1174
1230
  self._headers: Dict[str, str] = {}
1175
1231
  self._cluster_authed = False
1176
1232
  self.session = requests.Session()
@@ -1221,7 +1277,7 @@ class Client:
1221
1277
  response = self.session.get(url, headers=self._headers)
1222
1278
  if response.status_code != 200:
1223
1279
  raise RuntimeError(
1224
- f"Failed to fetch VLLM models. detail: {response.json()['detail']}"
1280
+ f"Failed to fetch VLLM models. detail: {_get_error_string(response)}"
1225
1281
  )
1226
1282
 
1227
1283
  try:
@@ -1238,7 +1294,9 @@ class Client:
1238
1294
 
1239
1295
  response = self.session.post(url, json=payload)
1240
1296
  if response.status_code != 200:
1241
- raise RuntimeError(f"Failed to login, detail: {response.json()['detail']}")
1297
+ raise RuntimeError(
1298
+ f"Failed to login, detail: {_get_error_string(response)}"
1299
+ )
1242
1300
 
1243
1301
  response_data = response.json()
1244
1302
  # Only bearer token for now
@@ -1455,7 +1513,8 @@ class Client:
1455
1513
  ) -> Dict[str, Any]:
1456
1514
  """Start an asynchronous parameter reload with the same model UID.
1457
1515
 
1458
- Engine changes require launch-time ``enable_weight_cache=True``;
1516
+ Engine changes require weight retention enabled at launch (automatic
1517
+ on supported configurations, or ``enable_weight_cache=True``);
1459
1518
  a standalone ``reasoning_content`` update does not. Use
1460
1519
  ``get_model_reload_status`` to wait for ready/error after HTTP 202.
1461
1520
  """
@@ -1474,6 +1533,16 @@ class Client:
1474
1533
  )
1475
1534
  return response.json()
1476
1535
 
1536
+ def get_model_runtime_info(self, model_uid: str) -> Dict[str, Any]:
1537
+ """Return runtime_context_length (tokens, or None) and per-replica limits."""
1538
+ url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/runtime"
1539
+ response = self.session.get(url, headers=self._headers)
1540
+ if response.status_code != 200:
1541
+ raise RuntimeError(
1542
+ f"Failed to get model runtime info, detail: {_get_error_string(response)}"
1543
+ )
1544
+ return response.json()
1545
+
1477
1546
  def get_model_reload_status(self, model_uid: str) -> Dict[str, Any]:
1478
1547
  """Return the latest reload operation, including its stage and error."""
1479
1548
  url = f"{self.base_url}/v1/models/{quote(model_uid, safe='')}/reload"
@@ -2082,15 +2151,42 @@ class Client:
2082
2151
  response_data = response.json()
2083
2152
  return response_data
2084
2153
 
2154
+ def check_component_update(
2155
+ self, component: str, worker_address: Optional[str] = None
2156
+ ) -> Dict[str, Any]:
2157
+ """Check the package source on the selected component's machine."""
2158
+ if component not in {"api", "supervisor", "worker"}:
2159
+ raise ValueError("Unknown component")
2160
+ if component == "worker":
2161
+ if not worker_address:
2162
+ raise ValueError("worker_address is required")
2163
+ path = f"workers/{quote(worker_address, safe='')}"
2164
+ else:
2165
+ path = component
2166
+ response = self.session.get(
2167
+ f"{self.base_url}/v1/{path}/updates", headers=self._headers
2168
+ )
2169
+ if response.status_code != 200:
2170
+ raise RuntimeError(
2171
+ f"Failed to check updates: {_get_error_string(response)}"
2172
+ )
2173
+ return response.json()
2174
+
2085
2175
  def relaunch_api(
2086
2176
  self,
2087
2177
  python_executable: Optional[str] = None,
2088
2178
  request_id: Optional[str] = None,
2179
+ *,
2180
+ version: Optional[str] = None,
2089
2181
  ) -> Dict[str, Any]:
2090
2182
  """Replace the distributed API process while existing requests drain."""
2091
2183
  response = self.session.post(
2092
2184
  f"{self.base_url}/v1/api/relaunch",
2093
- json={"python_executable": python_executable, "request_id": request_id},
2185
+ json={
2186
+ "python_executable": python_executable,
2187
+ "request_id": request_id,
2188
+ **({"version": version} if version is not None else {}),
2189
+ },
2094
2190
  headers=self._headers,
2095
2191
  )
2096
2192
  if response.status_code != 202:
@@ -2122,11 +2218,17 @@ class Client:
2122
2218
  self,
2123
2219
  python_executable: Optional[str] = None,
2124
2220
  request_id: Optional[str] = None,
2221
+ *,
2222
+ version: Optional[str] = None,
2125
2223
  ) -> Dict[str, Any]:
2126
2224
  """Replace the distributed Supervisor process while models remain running."""
2127
2225
  response = self.session.post(
2128
2226
  f"{self.base_url}/v1/supervisor/relaunch",
2129
- json={"python_executable": python_executable, "request_id": request_id},
2227
+ json={
2228
+ "python_executable": python_executable,
2229
+ "request_id": request_id,
2230
+ **({"version": version} if version is not None else {}),
2231
+ },
2130
2232
  headers=self._headers,
2131
2233
  )
2132
2234
  if response.status_code != 202:
@@ -2161,11 +2263,17 @@ class Client:
2161
2263
  worker_address: str,
2162
2264
  python_executable: Optional[str] = None,
2163
2265
  request_id: Optional[str] = None,
2266
+ *,
2267
+ version: Optional[str] = None,
2164
2268
  ) -> Dict[str, Any]:
2165
2269
  """Relaunch a Worker and return its asynchronous operation status."""
2166
2270
  response = self.session.post(
2167
2271
  f"{self.base_url}/v1/workers/{quote(worker_address, safe='')}/relaunch",
2168
- json={"python_executable": python_executable, "request_id": request_id},
2272
+ json={
2273
+ "python_executable": python_executable,
2274
+ "request_id": request_id,
2275
+ **({"version": version} if version is not None else {}),
2276
+ },
2169
2277
  headers=self._headers,
2170
2278
  )
2171
2279
  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.3.0
4
4
  Summary: Client for Xinference
5
5
  Home-page: https://github.com/xorbitsai/inference-client
6
6
  Author: Qin Xuye