-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathsync_api.py
More file actions
1801 lines (1572 loc) · 66.7 KB
/
sync_api.py
File metadata and controls
1801 lines (1572 loc) · 66.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Sync I/O protocol implementation for the LM Studio remote access API."""
import itertools
import time
import weakref
from abc import abstractmethod
from concurrent.futures import Future as SyncFuture, ThreadPoolExecutor, as_completed
from contextlib import (
contextmanager,
ExitStack,
)
from types import EllipsisType, TracebackType
from typing import (
Any,
ContextManager,
Generator,
Iterable,
Iterator,
Callable,
Generic,
Sequence,
Type,
TypeAlias,
TypeVar,
)
from typing_extensions import (
# Native in 3.11+
Self,
# Native in 3.13+
TypeIs,
)
import httpx
# Synchronous API still uses an async websocket (just in a background thread)
from httpx_ws import AsyncWebSocketSession
from .sdk_api import (
LMStudioRuntimeError,
LMStudioValueError,
sdk_callback_invocation,
sdk_public_api,
)
from .schemas import AnyLMStudioStruct, DictObject
from .history import (
AssistantResponse,
Chat,
ChatHistoryDataDict,
FileHandle,
LocalFileInput,
_LocalFileData,
ToolCallRequest,
ToolResultMessage,
)
from .json_api import (
ActResult,
AnyLoadConfig,
AnyModelSpecifier,
AvailableModelBase,
ChannelEndpoint,
ChannelHandler,
ChatResponseEndpoint,
ClientBase,
ClientSession,
CompletionEndpoint,
DEFAULT_TTL,
DownloadedModelBase,
DownloadFinalizedCallback,
DownloadProgressCallback,
EmbeddingLoadModelConfig,
EmbeddingLoadModelConfigDict,
EmbeddingModelInfo,
GetOrLoadEndpoint,
LlmInfo,
LlmLoadModelConfig,
LlmLoadModelConfigDict,
LlmPredictionConfig,
LlmPredictionConfigDict,
LlmPredictionFragment,
LMStudioCancelledError,
LMStudioClientError,
LMStudioPredictionError,
LMStudioTimeoutError,
LMStudioWebsocket,
LMStudioWebsocketError,
LoadModelEndpoint,
ModelDownloadOptionBase,
ModelHandleBase,
ModelInstanceInfo,
ModelLoadingCallback,
ModelSessionTypes,
ModelTypesEmbedding,
ModelTypesLlm,
PredictionEndpoint,
PredictionFirstTokenCallback,
PredictionFragmentCallback,
PredictionFragmentEvent,
PredictionMessageCallback,
PredictionResult,
PredictionRoundResult,
PredictionRxEvent,
PredictionStreamBase,
PredictionToolCallEvent,
PromptProcessingCallback,
RemoteCallHandler,
ResponseSchema,
TModelInfo,
ToolDefinition,
check_model_namespace,
load_struct,
_model_spec_to_api_dict,
_redact_json,
)
from ._ws_impl import SyncFutureTimeout
from ._ws_thread import AsyncWebsocketThread, SyncToAsyncWebsocketBridge
from ._kv_config import TLoadConfig, TLoadConfigDict, parse_server_config
from ._sdk_models import (
EmbeddingRpcCountTokensParameter,
EmbeddingRpcEmbedStringParameter,
EmbeddingRpcTokenizeParameter,
LlmApplyPromptTemplateOpts,
LlmApplyPromptTemplateOptsDict,
LlmRpcApplyPromptTemplateParameter,
ModelCompatibilityType,
)
from ._logging import new_logger, LogEventContext
# Only the sync API itself is published from
# this module. Anything needed for type hints
# and similar tasks is published from `json_api`.
# Bypassing the high level API, and working more
# directly with the underlying websocket(s) is
# supported (hence the public names), but they're
# not exported via the top-level `lmstudio` API.
__all__ = [
"AnyDownloadedModel",
"Client",
"DownloadedEmbeddingModel",
"DownloadedLlm",
"EmbeddingModel",
"LLM",
"SyncModelHandle",
"PredictionStream",
"configure_default_client",
"get_default_client",
"get_sync_api_timeout",
"embedding_model",
"list_downloaded_models",
"list_loaded_models",
"llm",
"prepare_image",
"set_sync_api_timeout",
]
#
_DEFAULT_TIMEOUT: float | None = 60.0
@sdk_public_api()
def get_sync_api_timeout() -> float | None:
"""Return the current default sync API timeout when waiting for server messages."""
return _DEFAULT_TIMEOUT
@sdk_public_api()
def set_sync_api_timeout(timeout: float | None) -> None:
"""Set the default sync API timeout when waiting for server messages."""
global _DEFAULT_TIMEOUT
if timeout is not None:
timeout = float(timeout)
_DEFAULT_TIMEOUT = timeout
T = TypeVar("T")
CallWithTimeout: TypeAlias = Callable[[float | None], Any]
TimeoutOption: TypeAlias = float | None | EllipsisType
class SyncChannel(Generic[T]):
"""Communication subchannel over multiplexed async websocket."""
def __init__(
self,
channel_id: int,
get_message: CallWithTimeout,
endpoint: ChannelEndpoint[T, Any, Any],
send_json: Callable[[DictObject], None],
log_context: LogEventContext,
timeout: TimeoutOption = ...,
) -> None:
"""Initialize synchronous websocket streaming channel."""
self._is_finished = False
self._get_message = get_message
self._send_json = send_json
self._timeout = timeout
self._api_channel = ChannelHandler(channel_id, endpoint, log_context)
def get_creation_message(self) -> DictObject:
"""Get the message to send to create this channel."""
return self._api_channel.get_creation_message()
def send_message(self, message: DictObject) -> None:
"""Send given message on this channel."""
wrapped_message = self._api_channel.wrap_message(message)
self._send_json(wrapped_message)
def cancel(self) -> None:
"""Cancel the channel."""
if self._is_finished:
return
cancel_message = self._api_channel.get_cancel_message()
self._send_json(cancel_message)
@property
def timeout(self) -> float | None:
"""Permitted time between received messages for this channel."""
timeout = self._timeout
if timeout is ...:
return _DEFAULT_TIMEOUT
return timeout
def rx_stream(
self,
) -> Iterator[DictObject | None]:
"""Stream received channel messages until channel is closed by server."""
while not self._is_finished:
with sdk_public_api():
# Avoid emitting tracebacks that delve into supporting libraries
# (we can't easily suppress the SDK's own frames for iterators)
try:
message = self._get_message(self.timeout)
except SyncFutureTimeout:
raise LMStudioTimeoutError from None
if message is None:
raise LMStudioWebsocketError("Client unexpectedly disconnected.")
contents = self._api_channel.handle_rx_message(message)
if contents is None:
self._is_finished = True
break
yield contents
def wait_for_result(self) -> T:
"""Wait for the channel to finish and return the result."""
endpoint = self._api_channel.endpoint
for contents in self.rx_stream():
endpoint.handle_message_events(contents)
if endpoint.is_finished:
break
return endpoint.result()
class SyncRemoteCall:
"""Remote procedure call over multiplexed async websocket."""
def __init__(
self,
call_id: int,
get_message: CallWithTimeout,
log_context: LogEventContext,
notice_prefix: str = "RPC",
timeout: TimeoutOption = ...,
) -> None:
"""Initialize synchronous remote procedure call."""
self._get_message = get_message
self._timeout = timeout
self._rpc = RemoteCallHandler(call_id, log_context, notice_prefix)
self._logger = logger = new_logger(type(self).__name__)
logger.update_context(log_context, call_id=call_id)
def get_rpc_message(
self, endpoint: str, params: AnyLMStudioStruct | None
) -> DictObject:
"""Get the message to send to initiate this remote procedure call."""
return self._rpc.get_rpc_message(endpoint, params)
@property
def timeout(self) -> float | None:
"""Permitted time to wait for a reply to this call."""
timeout = self._timeout
if timeout is ...:
return _DEFAULT_TIMEOUT
return timeout
def receive_result(self) -> Any:
"""Receive call response on the receive queue."""
try:
message = self._get_message(self.timeout)
except SyncFutureTimeout:
raise LMStudioTimeoutError from None
if message is None:
raise LMStudioWebsocketError("Client unexpectedly disconnected.")
return self._rpc.handle_rx_message(message)
class SyncLMStudioWebsocket(LMStudioWebsocket[SyncToAsyncWebsocketBridge]):
"""Synchronous websocket client that handles demultiplexing of reply messages."""
def __init__(
self,
ws_thread: AsyncWebsocketThread,
ws_url: str,
auth_details: DictObject,
log_context: LogEventContext | None = None,
) -> None:
"""Initialize synchronous websocket client."""
super().__init__(ws_url, auth_details, log_context)
self._ws_thread = ws_thread
@property
def _httpx_ws(self) -> AsyncWebSocketSession | None:
# Underlying HTTPX session is accessible for testing purposes
ws_thread = self._ws
if ws_thread is None:
return None
return ws_thread._ws
def __enter__(self) -> Self:
# Handle reentrancy the same way files do:
# allow nested use as a CM, but close on the first exit
if self._ws is None:
self.connect()
return self
def __exit__(self, *args: Any) -> None:
self.disconnect()
def connect(self) -> Self:
"""Connect to and authenticate with the LM Studio API."""
self._fail_if_connected("Attempted to connect already connected websocket")
ws = SyncToAsyncWebsocketBridge(
self._ws_thread,
self._ws_url,
self._auth_details,
self._logger.event_context,
)
if not ws.connect():
if ws._connection_failure is not None:
raise self._get_connection_failure_error(ws._connection_failure)
if ws._auth_failure is not None:
raise self._get_auth_failure_error(ws._auth_failure)
self._logger.error("Connection failed, but no failure reason reported.")
raise self._get_connection_failure_error()
self._ws = ws
return self
def disconnect(self) -> None:
"""Drop the LM Studio API connection."""
ws = self._ws
self._ws = None
if ws is not None:
self._logger.debug(f"Disconnecting websocket session ({self._ws_url})")
ws.notify_client_termination_threadsafe()
ws.disconnect()
self._logger.info(f"Websocket session disconnected ({self._ws_url})")
close = disconnect
def _send_json(self, message: DictObject) -> None:
# Callers are expected to call `_ensure_connected` before this method
ws = self._ws
assert ws is not None
# Background thread handles the exception conversion
ws.send_json(message)
def _connect_to_endpoint(self, channel: SyncChannel[Any]) -> None:
"""Connect channel to specified endpoint."""
self._ensure_connected("open channel endpoints")
create_message = channel.get_creation_message()
self._logger.debug("Connecting channel endpoint", json=create_message)
self._send_json(create_message)
@contextmanager
def open_channel(
self,
endpoint: ChannelEndpoint[T, Any, Any],
) -> Generator[SyncChannel[T], None, None]:
"""Open a streaming channel over the websocket."""
ws = self._ws
assert ws is not None
with ws.open_channel() as (channel_id, getter):
channel = SyncChannel(
channel_id,
getter,
endpoint,
self._send_json,
self._logger.event_context,
)
self._connect_to_endpoint(channel)
yield channel
def _send_call(
self,
rpc: SyncRemoteCall,
endpoint: str,
params: AnyLMStudioStruct | None = None,
) -> None:
"""Initiate remote call to specified endpoint."""
self._ensure_connected("send remote procedure call")
call_message = rpc.get_rpc_message(endpoint, params)
# TODO: Improve logging for large requests (such as file uploads)
# without requiring explicit special casing here
logged_message: DictObject
if call_message.get("endpoint") == "uploadFileBase64":
logged_message = _redact_json(call_message)
else:
logged_message = call_message
self._logger.debug("Sending RPC request", json=logged_message)
self._send_json(call_message)
def remote_call(
self,
endpoint: str,
params: AnyLMStudioStruct | None,
notice_prefix: str = "RPC",
) -> Any:
"""Make a remote procedure call over the websocket."""
ws = self._ws
assert ws is not None
with ws.start_call() as (call_id, getter):
rpc = SyncRemoteCall(
call_id, getter, self._logger.event_context, notice_prefix
)
self._send_call(rpc, endpoint, params)
return rpc.receive_result()
class _SyncSession(ClientSession["Client", SyncLMStudioWebsocket]):
"""Sync client session interfaces applicable to all API namespaces."""
def __init__(self, client: "Client") -> None:
"""Initialize synchronous API client session."""
super().__init__(client)
self._resources = ExitStack()
def _ensure_connected(self) -> None:
# Allow lazy connection of the session websocket
if self._lmsws is None:
self.connect()
def __enter__(self) -> Self:
# Handle reentrancy the same way files do:
# allow nested use as a CM, but close on the first exit
self._ensure_connected()
return self
def __exit__(self, *args: Any) -> None:
self.disconnect()
@sdk_public_api()
def connect(self) -> SyncLMStudioWebsocket:
"""Connect the client session."""
self._fail_if_connected("Attempted to connect already connected session")
api_host = self._client.api_host
namespace = self.API_NAMESPACE
if namespace is None:
raise LMStudioClientError(
f"No API namespace defined for {type(self).__name__}"
)
session_url = f"ws://{api_host}/{namespace}"
resources = self._resources
self._lmsws = lmsws = resources.enter_context(
SyncLMStudioWebsocket(
self._client._ws_thread, session_url, self._client._auth_details
)
)
return lmsws
@sdk_public_api()
def disconnect(self) -> None:
"""Disconnect the client session."""
self._lmsws = None
self._resources.close()
close = disconnect
# To allow for client level management of the session lifecycles
# without requiring network I/O on property access, we implicitly
# connect the websocket (if necessary) when sending requests
@contextmanager
def _create_channel(
self,
endpoint: ChannelEndpoint[T, Any, Any],
) -> Generator[SyncChannel[T], None, None]:
"""Connect a channel to an LM Studio streaming endpoint."""
self._ensure_connected()
lmsws = self._get_lmsws("create channels")
with lmsws.open_channel(endpoint) as channel:
yield channel
@sdk_public_api()
def remote_call(
self,
endpoint: str,
params: AnyLMStudioStruct | None = None,
notice_prefix: str = "RPC",
) -> Any:
"""Send a remote call to the given RPC endpoint and wait for the result."""
self._ensure_connected()
lmsws = self._get_lmsws("make remote calls")
return lmsws.remote_call(endpoint, params, notice_prefix)
TSyncSessionModel = TypeVar(
"TSyncSessionModel", bound="_SyncSessionModel[Any, Any, Any, Any]"
)
TModelHandle = TypeVar("TModelHandle", bound="SyncModelHandle[Any]")
class DownloadedModel(
Generic[
TModelInfo,
TSyncSessionModel,
TLoadConfig,
TLoadConfigDict,
TModelHandle,
],
DownloadedModelBase[TModelInfo, TSyncSessionModel],
):
@sdk_public_api()
def load_new_instance(
self,
*,
ttl: int | None = DEFAULT_TTL,
instance_identifier: str | None = None,
config: TLoadConfig | TLoadConfigDict | None = None,
on_load_progress: ModelLoadingCallback | None = None,
) -> TModelHandle:
"""Load this model with the given identifier and configuration.
Note: details of configuration fields may change in SDK feature releases.
"""
handle: TModelHandle = self._session._load_new_instance(
self.model_key, instance_identifier, ttl, config, on_load_progress
)
return handle
@sdk_public_api()
def model(
self,
*,
ttl: int | None = DEFAULT_TTL,
config: TLoadConfig | TLoadConfigDict | None = None,
on_load_progress: ModelLoadingCallback | None = None,
) -> TModelHandle:
"""Retrieve model with default identifier, or load it with given configuration.
Note: configuration of retrieved model is NOT checked against the given config.
Note: details of configuration fields may change in SDK feature releases.
"""
# Call _get_or_load directly, since we have a model identifier
handle: TModelHandle = self._session._get_or_load(
self.model_key, ttl, config, on_load_progress
)
return handle
class DownloadedEmbeddingModel(
DownloadedModel[
EmbeddingModelInfo,
"_SyncSessionEmbedding",
EmbeddingLoadModelConfig,
EmbeddingLoadModelConfigDict,
"EmbeddingModel",
],
):
"""Download listing for an embedding model."""
def __init__(
self, model_info: DictObject, session: "_SyncSessionEmbedding"
) -> None:
"""Initialize downloaded embedding model details."""
super().__init__(EmbeddingModelInfo, model_info, session)
class DownloadedLlm(
DownloadedModel[
LlmInfo,
"_SyncSessionLlm",
LlmLoadModelConfig,
LlmLoadModelConfigDict,
"LLM",
]
):
"""Download listing for an LLM."""
def __init__(self, model_info: DictObject, session: "_SyncSessionLlm") -> None:
"""Initialize downloaded embedding model details."""
super().__init__(LlmInfo, model_info, session)
AnyDownloadedModel: TypeAlias = DownloadedModel[Any, Any, Any, Any, Any]
class _SyncSessionSystem(_SyncSession):
"""Sync client session for the system namespace."""
API_NAMESPACE = "system"
@sdk_public_api()
def list_downloaded_models(self) -> Sequence[AnyDownloadedModel]:
"""Get the list of all downloaded models that are available for loading."""
# The list of downloaded models is only available via the system API namespace
models = self.remote_call("listDownloadedModels")
return [self._process_download_listing(m) for m in models]
def _process_download_listing(self, model_info: DictObject) -> AnyDownloadedModel:
model_type = model_info.get("type")
if model_type is None:
raise LMStudioClientError(
f"No 'type' field in download listing: {model_info}"
)
match model_type:
case "embedding":
return DownloadedEmbeddingModel(model_info, self._client.embedding)
case "llm":
return DownloadedLlm(model_info, self._client.llm)
raise LMStudioClientError(
f"Unknown model type {model_type!r} in download listing: {model_info}"
)
class _SyncSessionFiles(_SyncSession):
"""Sync client session for the files namespace."""
API_NAMESPACE = "files"
def _fetch_file_handle(self, file_data: _LocalFileData) -> FileHandle:
handle = self.remote_call("uploadFileBase64", file_data._as_fetch_param())
# Returned dict provides the handle identifier, file type, and size in bytes
# Add the extra fields needed for a FileHandle (aka ChatMessagePartFileData)
handle["name"] = file_data.name
handle["type"] = "file"
return load_struct(handle, FileHandle)
# Not yet implemented (server API only supports the same file types as prepare_image)
# @sdk_public_api()
def _prepare_file(self, src: LocalFileInput, name: str | None = None) -> FileHandle:
"""Add a file to the server. Returns a file handle for use in prediction requests."""
file_data = _LocalFileData(src, name)
return self._fetch_file_handle(file_data)
@sdk_public_api()
def prepare_image(self, src: LocalFileInput, name: str | None = None) -> FileHandle:
"""Add an image to the server. Returns a file handle for use in prediction requests."""
file_data = _LocalFileData(src, name)
return self._fetch_file_handle(file_data)
class ModelDownloadOption(ModelDownloadOptionBase[_SyncSession]):
"""A single download option for a model search result."""
@sdk_public_api()
def download(
self,
on_progress: DownloadProgressCallback | None = None,
on_finalize: DownloadFinalizedCallback | None = None,
) -> str:
"""Download a model and get its path for loading."""
endpoint = self._get_download_endpoint(on_progress, on_finalize)
with self._session._create_channel(endpoint) as channel:
return channel.wait_for_result()
class AvailableModel(AvailableModelBase[_SyncSession]):
"""A model available for download from the model repository."""
@sdk_public_api()
def get_download_options(
self,
) -> Sequence[ModelDownloadOption]:
"""Get the download options for the specified model."""
params = self._get_download_query_params()
options = self._session.remote_call("getModelDownloadOptions", params)
final = []
for m in options["results"]:
final.append(ModelDownloadOption(m, self._session))
return final
class _SyncSessionRepository(_SyncSession):
"""Sync client session for the repository namespace."""
API_NAMESPACE = "repository"
@sdk_public_api()
def search_models(
self,
search_term: str | None = None,
limit: int | None = None,
compatibility_types: list[ModelCompatibilityType] | None = None,
) -> Sequence[AvailableModel]:
"""Search for downloadable models satisfying a search query."""
params = self._get_model_search_params(search_term, limit, compatibility_types)
models = self.remote_call("searchModels", params)
return [AvailableModel(m, self) for m in models["results"]]
TDownloadedModel = TypeVar("TDownloadedModel", bound=AnyDownloadedModel)
class _SyncSessionModel(
_SyncSession,
Generic[TModelHandle, TLoadConfig, TLoadConfigDict, TDownloadedModel],
):
"""Sync client session for a model (LLM/embedding) namespace."""
_API_TYPES: Type[ModelSessionTypes[TLoadConfig]]
@property
def _system_session(self) -> _SyncSessionSystem:
return self._client.system
@property
def _files_session(self) -> _SyncSessionFiles:
return self._client.files
def _get_load_config(self, model_specifier: AnyModelSpecifier) -> AnyLoadConfig:
"""Get the model load config for the specified model."""
# Note that the configuration reported here uses the *server* config names,
# not the attributes used to set the configuration in the client SDK
params = self._API_TYPES.REQUEST_LOAD_CONFIG._from_api_dict(
{
"specifier": _model_spec_to_api_dict(model_specifier),
}
)
config = self.remote_call("getLoadConfig", params)
result_type = self._API_TYPES.MODEL_LOAD_CONFIG
return result_type._from_any_api_dict(parse_server_config(config))
def _get_api_model_info(self, model_specifier: AnyModelSpecifier) -> Any:
"""Get the raw model info (if any) for a model matching the given criteria."""
params = self._API_TYPES.REQUEST_MODEL_INFO._from_api_dict(
{
"specifier": _model_spec_to_api_dict(model_specifier),
"throwIfNotFound": True,
}
)
return self.remote_call("getModelInfo", params)
@sdk_public_api()
def get_model_info(self, model_specifier: AnyModelSpecifier) -> ModelInstanceInfo:
"""Get the model info (if any) for a model matching the given criteria."""
response = self._get_api_model_info(model_specifier)
model_info = self._API_TYPES.MODEL_INSTANCE_INFO._from_any_api_dict(response)
return model_info
def _get_context_length(self, model_specifier: AnyModelSpecifier) -> int:
"""Get the context length of the specified model."""
raw_model_info = self._get_api_model_info(model_specifier)
return int(raw_model_info.get("contextLength", -1))
def _count_tokens(self, model_specifier: AnyModelSpecifier, input: str) -> int:
params = EmbeddingRpcCountTokensParameter._from_api_dict(
{
"specifier": _model_spec_to_api_dict(model_specifier),
"inputString": input,
}
)
response = self.remote_call("countTokens", params)
return int(response["tokenCount"])
# Private helper method to allow the main API to easily accept iterables
def _tokenize_text(
self, model_specifier: AnyModelSpecifier, input: str
) -> Sequence[int]:
params = EmbeddingRpcTokenizeParameter._from_api_dict(
{
"specifier": _model_spec_to_api_dict(model_specifier),
"inputString": input,
}
)
response = self.remote_call("tokenize", params)
return response.get("tokens", []) if response else []
# Alas, type hints don't properly support distinguishing str vs Iterable[str]:
# https://github.com/python/typing/issues/256
def _tokenize(
self, model_specifier: AnyModelSpecifier, input: str | Iterable[str]
) -> Sequence[int] | Sequence[Sequence[int]]:
"""Tokenize the input string(s) using the specified model."""
if isinstance(input, str):
return self._tokenize_text(model_specifier, input)
return [self._tokenize_text(model_specifier, i) for i in input]
@abstractmethod
def _create_handle(self, model_identifier: str) -> TModelHandle:
"""Get a symbolic handle to the specified model."""
...
@sdk_public_api()
def model(
self,
model_key: str | None = None,
/,
*,
ttl: int | None = DEFAULT_TTL,
config: TLoadConfig | TLoadConfigDict | None = None,
on_load_progress: ModelLoadingCallback | None = None,
) -> TModelHandle:
"""Get a handle to the specified model (loading it if necessary).
Note: configuration of retrieved model is NOT checked against the given config.
Note: details of configuration fields may change in SDK feature releases.
"""
if model_key is None:
# Should this raise an error if a config is supplied?
return self._get_any()
return self._get_or_load(model_key, ttl, config, on_load_progress)
@sdk_public_api()
def list_loaded(self) -> Sequence[TModelHandle]:
"""Get the list of currently loaded models."""
models = self.remote_call("listLoaded")
return [self._create_handle(m["identifier"]) for m in models]
@sdk_public_api()
def unload(self, model_identifier: str) -> None:
"""Unload the specified model."""
params = self._API_TYPES.REQUEST_UNLOAD(identifier=model_identifier)
self.remote_call("unloadModel", params)
# N.B. Canceling a load from the UI doesn't update the load process for a while.
# Fortunately, this is not our fault. The server just delays in broadcasting it.
@sdk_public_api()
def load_new_instance(
self,
model_key: str,
instance_identifier: str | None = None,
*,
ttl: int | None = DEFAULT_TTL,
config: TLoadConfig | TLoadConfigDict | None = None,
on_load_progress: ModelLoadingCallback | None = None,
) -> TModelHandle:
"""Load the specified model with the given identifier and configuration.
Note: details of configuration fields may change in SDK feature releases.
"""
return self._load_new_instance(
model_key, instance_identifier, ttl, config, on_load_progress
)
def _load_new_instance(
self,
model_key: str,
instance_identifier: str | None,
ttl: int | None,
config: TLoadConfig | TLoadConfigDict | None,
on_load_progress: ModelLoadingCallback | None,
) -> TModelHandle:
channel_type = self._API_TYPES.REQUEST_NEW_INSTANCE
config_type = self._API_TYPES.MODEL_LOAD_CONFIG
endpoint = LoadModelEndpoint(
model_key,
instance_identifier,
ttl,
channel_type,
config_type,
config,
on_load_progress,
)
with self._create_channel(endpoint) as channel:
result = channel.wait_for_result()
return self._create_handle(result.identifier)
def _get_or_load(
self,
model_key: str,
ttl: int | None,
config: TLoadConfig | TLoadConfigDict | None,
on_load_progress: ModelLoadingCallback | None,
) -> TModelHandle:
"""Get the specified model if it is already loaded, otherwise load it."""
channel_type = self._API_TYPES.REQUEST_GET_OR_LOAD
config_type = self._API_TYPES.MODEL_LOAD_CONFIG
endpoint = GetOrLoadEndpoint(
model_key, ttl, channel_type, config_type, config, on_load_progress
)
with self._create_channel(endpoint) as channel:
result = channel.wait_for_result()
return self._create_handle(result.identifier)
def _get_any(self) -> TModelHandle:
"""Get a handle to any loaded model."""
loaded_models = self.list_loaded()
if not loaded_models:
raise LMStudioClientError(
f"Could not get model handle in namespace {self.API_NAMESPACE} (no models are currently loaded)."
)
return self._create_handle(loaded_models[0].identifier)
@classmethod
def _is_relevant_model(cls, model: AnyDownloadedModel) -> TypeIs[TDownloadedModel]:
return bool(model.type == cls.API_NAMESPACE)
@sdk_public_api()
def list_downloaded(self) -> Sequence[TDownloadedModel]:
"""Get the list of currently downloaded models that are available for loading."""
models = self._system_session.list_downloaded_models()
return [m for m in models if self._is_relevant_model(m)]
def _fetch_file_handle(self, file_data: _LocalFileData) -> FileHandle:
return self._files_session._fetch_file_handle(file_data)
SyncPredictionChannel: TypeAlias = SyncChannel[PredictionResult]
SyncPredictionCM: TypeAlias = ContextManager[SyncPredictionChannel]
class PredictionStream(PredictionStreamBase):
"""Sync context manager for an ongoing prediction process."""
def __init__(
self,
channel_cm: SyncPredictionCM,
endpoint: PredictionEndpoint,
) -> None:
"""Initialize a prediction process representation."""
self._resources = ExitStack()
self._channel_cm: SyncPredictionCM = channel_cm
self._channel: SyncPredictionChannel | None = None
super().__init__(endpoint)
@sdk_public_api()
def start(self) -> None:
"""Send the prediction request."""
if self._is_finished:
raise LMStudioRuntimeError("Prediction result has already been received.")
if self._is_started:
raise LMStudioRuntimeError("Prediction request has already been sent.")
# The given channel context manager is set up to send the relevant request
self._channel = self._resources.enter_context(self._channel_cm)
self._mark_started()
@sdk_public_api()
def close(self) -> None:
"""Terminate the prediction processing (if not already terminated)."""
# Cancel the prediction (if unfinished) and release acquired resources
if self._is_started and not self._is_finished:
self._set_error(
LMStudioCancelledError(
"Prediction cancelled unexpectedly: please use .cancel()"
)
)
self._channel = None
self._resources.close()
def __enter__(self) -> Self:
if self._channel is None:
self.start()
return self
def __exit__(
self,
_exc_type: Type[BaseException] | None,
exc_val: BaseException | None,
_exc_tb: TracebackType | None,
) -> None:
if exc_val and not self._is_finished:
self._set_error(exc_val)
self.close()
def __iter__(self) -> Iterator[LlmPredictionFragment]:
for event in self._iter_events():
if isinstance(event, PredictionFragmentEvent):
yield event.arg
def _iter_events(self) -> Iterator[PredictionRxEvent]:
endpoint = self._endpoint
with self:
assert self._channel is not None
for contents in self._channel.rx_stream():
for event in endpoint.iter_message_events(contents):
endpoint.handle_rx_event(event)
yield event
if endpoint.is_finished:
break
self._mark_finished()
@sdk_public_api()
def wait_for_result(self) -> PredictionResult:
"""Wait for the result of the prediction."""
for _ in self:
pass
return self.result()
@sdk_public_api()
def cancel(self) -> None:
"""Cancel the prediction process."""
if not self._is_finished and self._channel:
self._mark_cancelled()
self._channel.cancel()
class _SyncSessionLlm(
_SyncSessionModel[
"LLM",
LlmLoadModelConfig,