-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathjson_api.py
More file actions
2381 lines (2049 loc) · 91.4 KB
/
json_api.py
File metadata and controls
2381 lines (2049 loc) · 91.4 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
"""Common protocol implementation for the LM Studio remote access API."""
# In order to simplify the websocket demultiplexing logic, this is NOT
# a full sans I/O protocol implementation. Instead, it is an async
# protocol implementation that supports both async interaction
# (from the same event loop or from one running in another thread)
# *and* sync interaction (by blocking on threadsafe futures)
#
# The I/O *transport* layer is still abstracted out, but the internal
# use of asynchronous queues for message demultiplexing is assumed.
import asyncio
import copy
import inspect
import json
import os
import re
import sys
import uuid
import warnings
from abc import ABC, abstractmethod
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import (
Any,
Callable,
Coroutine,
Generator,
Generic,
Iterable,
Iterator,
Mapping,
Sequence,
Type,
TypeAlias,
TypedDict,
TypeVar,
cast,
get_type_hints,
overload,
)
from typing_extensions import (
# Native in 3.11+
assert_never,
NoReturn,
NotRequired,
Self,
)
import httpx
from msgspec import Struct, convert, defstruct, to_builtins
from . import _api_server_ports
from .sdk_api import (
LMStudioError,
LMStudioRuntimeError,
LMStudioValueError,
sdk_callback_invocation,
sdk_public_api,
sdk_public_type,
_truncate_traceback,
)
from .history import AssistantResponse, Chat, ToolCallRequest, ToolCallResultData
from .schemas import (
AnyLMStudioStruct,
DictObject,
LMStudioStruct,
TWireFormat,
_format_json,
_snake_case_keys_to_camelCase,
_to_json_schema,
)
from ._kv_config import (
ResponseSchema,
TLoadConfig,
TLoadConfigDict,
load_config_to_kv_config_stack,
parse_llm_load_config,
parse_prediction_config,
prediction_config_to_kv_config_stack,
)
from ._sdk_models import (
DownloadModelChannelRequest,
DownloadModelChannelRequestDict,
DownloadProgressUpdate,
EmbeddingChannelLoadModelCreationParameter,
EmbeddingChannelLoadModelCreationParameterDict,
EmbeddingChannelGetOrLoadCreationParameter,
EmbeddingChannelGetOrLoadCreationParameterDict,
EmbeddingLoadModelConfig,
EmbeddingLoadModelConfigDict,
EmbeddingModelInfo,
EmbeddingModelInstanceInfo,
EmbeddingRpcGetLoadConfigParameter,
EmbeddingRpcGetModelInfoParameter,
EmbeddingRpcTokenizeParameter,
EmbeddingRpcUnloadModelParameter,
KvConfigStack,
LlmChannelLoadModelCreationParameter,
LlmChannelLoadModelCreationParameterDict,
LlmChannelGetOrLoadCreationParameter,
LlmChannelGetOrLoadCreationParameterDict,
LlmInfo,
LlmInstanceInfo,
LlmLoadModelConfig,
LlmLoadModelConfigDict,
LlmPredictionConfig,
LlmPredictionConfigDict,
LlmPredictionFragment,
LlmPredictionStats,
LlmRpcGetLoadConfigParameter,
LlmRpcGetModelInfoParameter,
LlmRpcTokenizeParameter,
LlmRpcUnloadModelParameter,
LlmTool,
LlmToolUseSettingToolArray,
ModelCompatibilityType,
ModelInfo,
ModelInstanceInfo,
ModelSearchOptsDict,
ModelSearchResultDownloadOptionData,
ModelSearchResultEntryData,
ModelSpecifier,
ModelSpecifierDict,
ModelSpecifierInstanceReference,
ModelSpecifierQuery,
ModelQuery,
ModelQueryDict,
PredictionChannelRequest,
PredictionChannelRequestDict,
RepositoryRpcGetModelDownloadOptionsParameter,
RepositoryRpcSearchModelsParameter,
SerializedLMSExtendedError,
)
from ._logging import new_logger, LogEventContext, StructuredLogger
# The sync and async modules publish the main SDK client API.
# From here, we publish everything that might be needed
# for API type hints, error handling, defining custom
# structured responses, and other expected activities.
# The shared API itself is *not* automatically exported.
# If API consumers want to use that, they need to access it
# explicitly via `lmstudio.json_api`, it isn't exported
# implicitly as part of the top-level `lmstudio` API.
__all__ = [
"ActResult",
"AnyLoadConfig",
"AnyModelSpecifier",
"DownloadFinalizedCallback",
"DownloadProgressCallback",
"DownloadProgressUpdate",
"EmbeddingModelInfo",
"EmbeddingModelInstanceInfo",
"EmbeddingLoadModelConfig",
"EmbeddingLoadModelConfigDict",
"LlmInfo",
"LlmInstanceInfo",
"LlmLoadModelConfig",
"LlmLoadModelConfigDict",
"LlmPredictionConfig",
"LlmPredictionConfigDict",
"LlmPredictionFragment",
"LlmPredictionStats",
"LMStudioCancelledError",
"LMStudioClientError",
"LMStudioChannelClosedError",
"LMStudioModelNotFoundError",
"LMStudioPredictionError",
"LMStudioPresetNotFoundError",
"LMStudioServerError",
"LMStudioTimeoutError",
"LMStudioUnknownMessageWarning",
"LMStudioWebsocketError",
"ModelInfo",
"ModelInstanceInfo",
"ModelLoadResult",
"ModelSpecifier",
"ModelSpecifierDict",
"ModelQuery",
"ModelQueryDict",
"PredictionFirstTokenCallback",
"PredictionFragmentCallback",
"PredictionMessageCallback",
"PredictionResult",
"PredictionRoundResult",
"PromptProcessingCallback",
"ResponseSchema",
"SerializedLMSExtendedError",
"ToolDefinition",
"ToolFunctionDef",
"ToolFunctionDefDict",
]
T = TypeVar("T")
TStruct = TypeVar("TStruct", bound=AnyLMStudioStruct)
DEFAULT_TTL = 60 * 60 # By default, leaves idle models loaded for an hour
# lmstudio-js and lmstudio-python use the same API token environment variable
_ENV_API_TOKEN = "LM_API_TOKEN"
_LMS_API_TOKEN_REGEX = re.compile(
r"^sk-lm-(?P<clientIdentifier>[A-Za-z0-9]{8}):(?P<clientPasskey>[A-Za-z0-9]{20})$"
)
# Require a coroutine (not just any awaitable) for run_coroutine_threadsafe compatibility
SendMessageAsync: TypeAlias = Callable[[DictObject], Coroutine[Any, Any, None]]
UnstructuredPrediction: TypeAlias = str
StructuredPrediction: TypeAlias = DictObject
AnyPrediction = StructuredPrediction | UnstructuredPrediction
AnyModelSpecifier: TypeAlias = str | ModelSpecifier | ModelQuery | DictObject
AnyLoadConfig: TypeAlias = EmbeddingLoadModelConfig | LlmLoadModelConfig
GetOrLoadChannelRequest: TypeAlias = (
EmbeddingChannelGetOrLoadCreationParameter | LlmChannelGetOrLoadCreationParameter
)
GetOrLoadChannelRequestDict: TypeAlias = (
EmbeddingChannelGetOrLoadCreationParameterDict
| LlmChannelGetOrLoadCreationParameterDict
)
LoadModelChannelRequest: TypeAlias = (
EmbeddingChannelLoadModelCreationParameter | LlmChannelLoadModelCreationParameter
)
LoadModelChannelRequestDict: TypeAlias = (
EmbeddingChannelLoadModelCreationParameterDict
| LlmChannelLoadModelCreationParameterDict
)
LoadConfigRequest: TypeAlias = (
EmbeddingRpcGetLoadConfigParameter | LlmRpcGetLoadConfigParameter
)
ModelInfoRequest: TypeAlias = (
EmbeddingRpcGetModelInfoParameter | LlmRpcGetModelInfoParameter
)
TokenizeRequest: TypeAlias = EmbeddingRpcTokenizeParameter | LlmRpcTokenizeParameter
UnloadModelRequest: TypeAlias = (
EmbeddingRpcUnloadModelParameter | LlmRpcUnloadModelParameter
)
class ModelSessionTypes(Generic[TLoadConfig]):
"""Helper class to group related types for code sharing across model namespaces."""
# Prefer union types for simplicity, but declare as generic when beneficial
MODEL_INFO: Type[ModelInfo]
MODEL_INSTANCE_INFO: Type[ModelInstanceInfo]
MODEL_LOAD_CONFIG: Type[TLoadConfig]
REQUEST_GET_OR_LOAD: Type[GetOrLoadChannelRequest]
REQUEST_LOAD_CONFIG: Type[LoadConfigRequest]
REQUEST_MODEL_INFO: Type[ModelInfoRequest]
REQUEST_NEW_INSTANCE: Type[LoadModelChannelRequest]
REQUEST_TOKENIZE: Type[TokenizeRequest]
REQUEST_UNLOAD: Type[UnloadModelRequest]
class ModelTypesEmbedding(ModelSessionTypes[EmbeddingLoadModelConfig]):
"""Relevant structs for the embedding model namespace."""
MODEL_INFO = EmbeddingModelInfo
MODEL_INSTANCE_INFO = EmbeddingModelInstanceInfo
MODEL_LOAD_CONFIG = EmbeddingLoadModelConfig
REQUEST_GET_OR_LOAD = EmbeddingChannelGetOrLoadCreationParameter
REQUEST_LOAD_CONFIG = EmbeddingRpcGetLoadConfigParameter
REQUEST_MODEL_INFO = EmbeddingRpcGetModelInfoParameter
REQUEST_NEW_INSTANCE = EmbeddingChannelLoadModelCreationParameter
REQUEST_TOKENIZE = EmbeddingRpcTokenizeParameter
REQUEST_UNLOAD = EmbeddingRpcUnloadModelParameter
class ModelTypesLlm(ModelSessionTypes[LlmLoadModelConfig]):
"""Relevant structs for the LLM namespace."""
MODEL_INFO = LlmInfo
MODEL_INSTANCE_INFO = LlmInstanceInfo
MODEL_LOAD_CONFIG = LlmLoadModelConfig
REQUEST_GET_OR_LOAD = LlmChannelGetOrLoadCreationParameter
REQUEST_LOAD_CONFIG = LlmRpcGetLoadConfigParameter
REQUEST_MODEL_INFO = LlmRpcGetModelInfoParameter
REQUEST_NEW_INSTANCE = LlmChannelLoadModelCreationParameter
REQUEST_TOKENIZE = LlmRpcTokenizeParameter
REQUEST_UNLOAD = LlmRpcUnloadModelParameter
def _model_spec_to_api_dict(model_spec: AnyModelSpecifier) -> ModelSpecifierDict:
spec: ModelSpecifier
query: ModelQuery | None = None
if isinstance(model_spec, dict):
# Ensure snake case keys pattern match correctly
model_spec = cast(
ModelSpecifierDict | ModelQueryDict,
_snake_case_keys_to_camelCase(model_spec),
)
match model_spec:
case str():
# Accept a plain string as a shorthand for an identifier query
query = ModelQuery(identifier=model_spec)
case ModelSpecifierQuery() | ModelSpecifierInstanceReference():
# Accept full typed model specifications as structs
spec = model_spec
case ModelQuery():
# Accept an instance reference as a dict
query = model_spec
case {"type": "query"}:
# Accept a full query specifier as a dict
spec = ModelSpecifierQuery._from_any_api_dict(model_spec)
case {"type": "instanceReference"}:
# Accept an instance reference as a dict
spec = ModelSpecifierInstanceReference._from_any_api_dict(model_spec)
case {}:
# Accept an instance reference as a dict
query = ModelQuery._from_any_api_dict(model_spec)
case _:
raise LMStudioValueError(f"Unable to parse model specifier: {model_spec}")
if query is not None:
spec = ModelSpecifierQuery(query=query)
return spec.to_dict()
def load_struct(raw_data: DictObject, data_model: Type[TStruct]) -> TStruct:
"""Convert a builtin dictionary to a LMStudioStruct (msgspec.Struct) instance."""
return convert(raw_data, data_model)
def _get_data_lines(data: DictObject, prefix: str = "") -> Sequence[str]:
return [f"{prefix}{line}" for line in _format_json(data).splitlines()]
@sdk_public_type
class LMStudioServerError(LMStudioError):
"""Problems reported by the LM Studio instance."""
_raw_error: DictObject | None
server_error: SerializedLMSExtendedError | None
def __init__(self, message: str, details: DictObject | None = None) -> None:
"""Initialize with SDK message and remote error details."""
if details is None:
self._raw_error = self.server_error = None
formatted_message = message
else:
raw_details: DictObject
try:
raw_details = dict(details)
except ValueError:
# Server *should* be providing the details as an error dict,
# but avoid crashing if it sends a string or array instead
raw_details = {
"title": "Server API error",
"cause": str(details),
}
raw_details.pop("stack", None)
self._raw_error = raw_details
try:
parsed_details = SerializedLMSExtendedError._from_any_api_dict(
raw_details
)
text_details = self._format_server_error(parsed_details)
except Exception:
parsed_details = SerializedLMSExtendedError()
text_details = _format_json(raw_details)
self.server_error = parsed_details
formatted_message = f"{message}: {text_details}"
super().__init__(formatted_message)
@staticmethod
def _format_server_error(details: SerializedLMSExtendedError) -> str:
if details.title:
if details.root_title and details.root_title != details.title:
header = f"{details.root_title}: {details.title}"
else:
header = details.title
elif details.root_title:
header = details.root_title
else:
header = "Unknown remote error"
lines: list[str] = []
if details.display_data is not None:
lines.extend(("", " Additional information from server:"))
lines.extend(_get_data_lines(details.display_data, " "))
if details.error_data is not None:
lines.extend(("", " Error details from server:"))
lines.extend(_get_data_lines(details.error_data, " "))
if details.cause is not None:
lines.extend(("", " Reported cause:"))
lines.append(f" {details.cause}")
if details.suggestion is not None:
lines.extend(("", " Suggested potential remedy:"))
lines.append(f" {details.suggestion}")
# Only use the multi-line format if at least one
# of the extended error fields is populated
if lines:
additional_text = "\n".join(lines)
return f"\n\n {header}\n{additional_text}"
return header
@staticmethod
def from_details(message: str, details: DictObject) -> "LMStudioServerError":
"""Return appropriate class with SDK message and server error details."""
default_error = LMStudioServerError(message, details)
parsed_details = default_error.server_error
if parsed_details is None:
return default_error
display_data = parsed_details.display_data
if display_data:
specific_error: LMStudioServerError | None = None
match display_data:
case {"code": "generic.noModelMatchingQuery"} | {
"code": "generic.pathNotFound"
}:
specific_error = LMStudioModelNotFoundError(str(default_error))
case {"code": "generic.presetNotFound"}:
specific_error = LMStudioPresetNotFoundError(str(default_error))
if specific_error is not None:
specific_error._raw_error = default_error._raw_error
specific_error.server_error = default_error.server_error
return specific_error
return default_error
@sdk_public_type
class LMStudioModelNotFoundError(LMStudioServerError):
"""No model matching the given specifier could be located on the server."""
@sdk_public_type
class LMStudioPresetNotFoundError(LMStudioServerError):
"""No preset config matching the given identifier could be located on the server."""
@sdk_public_type
class LMStudioChannelClosedError(LMStudioServerError):
"""Streaming channel unexpectedly closed by the LM Studio instance."""
def __init__(self, message: str) -> None:
"""Initialize with SDK message."""
super().__init__(message, None)
@sdk_public_type
class LMStudioPredictionError(LMStudioServerError):
"""Problems reported by the LM Studio instance during a model prediction."""
@sdk_public_type
class LMStudioClientError(LMStudioError):
"""Problems identified locally in the SDK client."""
@sdk_public_type
class LMStudioUnknownMessageWarning(LMStudioClientError, UserWarning):
"""Client has received a message in a format it wasn't expecting."""
@sdk_public_type
class LMStudioCancelledError(LMStudioClientError):
"""Requested operation was cancelled via the SDK client session."""
@sdk_public_type
class LMStudioTimeoutError(LMStudioError, TimeoutError):
"""Client failed to receive a message from the server in the expected time."""
@sdk_public_type
class LMStudioWebsocketError(LMStudioClientError):
"""Client websocket session has terminated (or was never opened)."""
# dataclass vs LMStudioStruct:
#
# LMStudioStruct is specifically designed to handle serialisation
# to and from JSON-compatible dicts with camelCase keys.
#
# For SDK-only record types that are never serialised to or
# from JSON-compatible dicts, use data classes instead.
@dataclass(kw_only=True, frozen=True, slots=True)
class ModelLoadResult:
"""Details of a loaded LM Studio model."""
identifier: str
instance_reference: str
path: str
@dataclass(kw_only=True, frozen=True, slots=True)
class PredictionResult:
"""The final result of a prediction."""
# fmt: off
content: str # The text content of the prediction
parsed: AnyPrediction # dict for structured predictions, str otherwise
stats: LlmPredictionStats # Statistics about the prediction process
model_info: LlmInfo # Information about the model used
structured: bool = field(init=False) # Whether the result is structured or not
load_config: LlmLoadModelConfig # The configuration used to load the model
prediction_config: LlmPredictionConfig # The configuration used for the prediction
# fmt: on
def __post_init__(self) -> None:
# Instances are frozen, so `self.structured` can't be set directly
object.__setattr__(self, "structured", self.parsed is not self.content)
def __repr__(self) -> str:
return f"{type(self).__name__}(content={self.content!r})"
def __str__(self) -> str:
if self.structured:
return _format_json(self.parsed)
return self.content
def _to_history_content(self) -> str:
return self.content
@dataclass(kw_only=True, frozen=True, slots=True)
class PredictionRoundResult(PredictionResult):
"""The result of a prediction within a multi-round tool using action."""
round_index: int # The round within the action that produced this result
@classmethod
def from_result(cls, result: PredictionResult, round_index: int) -> Self:
"""Create a prediction round result from its underlying prediction result."""
copied_keys = {
k: getattr(result, k)
for k, v in result.__dataclass_fields__.items()
if v.init
}
return cls(round_index=round_index, **copied_keys)
@dataclass(kw_only=True, frozen=True, slots=True)
class ActResult:
"""Summary of a completed multi-round tool using action."""
# Detailed action results are reported via callbacks (for now)
# fmt: off
rounds: int
total_time_seconds: float
# fmt: on
@overload
def _redact_json(data: DictObject) -> DictObject: ...
@overload
def _redact_json(data: None) -> None: ...
def _redact_json(data: DictObject | None) -> DictObject | None:
"""Show top level structure without any substructure details."""
if data is None:
return None
redacted: dict[str, Any] = {}
for k, v in data.items():
match v:
case {}:
redacted[k] = {"...": "..."}
case [*_]:
redacted[k] = ["..."]
case _:
redacted[k] = v
return redacted
RxQueue: TypeAlias = asyncio.Queue[Any]
class MultiplexingManager:
"""Helper class to allocate distinct protocol multiplexing IDs."""
def __init__(self, logger: StructuredLogger) -> None:
"""Initialize ID multiplexer."""
self._open_channels: dict[int, RxQueue] = {}
self._last_channel_id = 0
self._pending_calls: dict[int, RxQueue] = {}
self._last_call_id = 0
# `_active_subscriptions` (if we add signal support)
# `_last_subscriber_id` (if we add signal support)
self._logger = logger
def all_queues(self) -> Iterator[asyncio.Queue[Any]]:
"""Iterate over all queues (for example, to send a shutdown message)."""
yield from self._open_channels.values()
yield from self._pending_calls.values()
# yield from self._active_subscriptions.values()
def _get_next_channel_id(self) -> int:
"""Get next distinct channel ID."""
next_id = self._last_channel_id + 1
self._last_channel_id = next_id
return next_id
def acquire_channel_id(self, rx_queue: RxQueue) -> int:
"""Acquire a distinct streaming channel ID for the given queue."""
channel_id = self._get_next_channel_id()
self._open_channels[channel_id] = rx_queue
return channel_id
def release_channel_id(self, channel_id: int, rx_queue: RxQueue) -> None:
"""Release a previously acquired streaming channel ID."""
open_channels = self._open_channels
# this Use pop to safely remove the channel, even if already gone
assigned_queue = open_channels.pop(channel_id, None)
# Make cleanup more forgiving log warnings instead of raising
if assigned_queue is None:
self._logger.warning(
f"Channel {channel_id} already released or never acquired",
channel_id=channel_id,
)
elif rx_queue is not assigned_queue:
# Queue mismatch is suspicious but shouldn't prevent cleanup
self._logger.warning(
f"Channel {channel_id} queue mismatch during release "
f"(expected {rx_queue!r}, found {assigned_queue!r})",
channel_id=channel_id,
)
@contextmanager
def assign_channel_id(self, rx_queue: RxQueue) -> Generator[int, None, None]:
"""Assign distinct streaming channel ID to given queue."""
channel_id = self.acquire_channel_id(rx_queue)
try:
yield channel_id
finally:
self.release_channel_id(channel_id, rx_queue)
def _get_next_call_id(self) -> int:
"""Get next distinct RPC ID."""
next_id = self._last_call_id + 1
self._last_call_id = next_id
return next_id
def acquire_call_id(self, rx_queue: RxQueue) -> int:
"""Acquire a distinct remote call ID for the given queue."""
call_id = self._get_next_call_id()
self._pending_calls[call_id] = rx_queue
return call_id
def release_call_id(self, call_id: int, rx_queue: RxQueue) -> None:
"""Release a previously acquired remote call ID."""
pending_calls = self._pending_calls
# Use pop to safely remove the call, even if already gone
assigned_queue = pending_calls.pop(call_id, None)
# Make cleanup more forgiving log warnings instead of raising
if assigned_queue is None:
self._logger.warning(
f"Remote call {call_id} already released or never acquired",
call_id=call_id,
)
elif rx_queue is not assigned_queue:
# Queue mismatch is suspicious but shouldn't prevent cleanup
self._logger.warning(
f"Remote call {call_id} queue mismatch during release "
f"(expected {rx_queue!r}, found {assigned_queue!r})",
call_id=call_id,
)
@contextmanager
def assign_call_id(self, rx_queue: RxQueue) -> Generator[int, None, None]:
"""Assign distinct remote call ID to given queue."""
call_id = self.acquire_call_id(rx_queue)
try:
yield call_id
finally:
self.release_call_id(call_id, rx_queue)
def map_rx_message(self, message: DictObject) -> RxQueue | None:
"""Map received message to the relevant demultiplexing queue."""
# TODO: Define an even-spammier-than-debug trace logging level for this
# self._logger.trace("Incoming websocket message", json=message)
rx_queue: RxQueue | None = None
match message:
case {"channelId": channel_id}:
rx_queue = self._open_channels.get(channel_id, None)
if rx_queue is None:
if channel_id <= self._last_channel_id:
if message.get("type") == "channelClose":
# Ignore close messages for channels that were already closed
pass
else:
self._logger.warn(
f"Received unhandled message {message} for already closed channel",
channel_id=channel_id,
)
else:
self._logger.warn(
f"Received message {message} for not yet used channel",
channel_id=channel_id,
)
case {"callId": call_id}:
rx_queue = self._pending_calls.get(call_id, None)
if rx_queue is None:
self._logger.warn(
"Received response to unknown call", call_id=call_id
)
case {"type": "communicationWarning", "warning": warning}:
# The SDK should NOT be causing protocol warnings, so log this as an error
self._logger.error("SDK communication warning", warning=warning)
return None
case unmatched:
raise LMStudioClientError(f"Unexpected message: {unmatched}")
return rx_queue
def map_tx_message(self, message: DictObject) -> RxQueue | None:
"""Map failed message transmission to the relevant demultiplexing queue."""
# TODO: Define an even-spammier-than-debug trace logging level for this
# self._logger.trace("Failed to send websocket message", json=message)
rx_queue: RxQueue | None = None
match message:
case {"channelId": channel_id}:
rx_queue = self._open_channels.get(channel_id, None)
if rx_queue is None:
if channel_id <= self._last_channel_id:
self._logger.warn(
"Attempted to send message on already closed channel",
channel_id=channel_id,
)
else:
self._logger.warn(
"Attempted to send message on not yet used channel",
channel_id=channel_id,
)
case {"callId": call_id}:
rx_queue = self._pending_calls.get(call_id, None)
if rx_queue is None:
self._logger.warn(
"Attempted to send remote call with unknown ID", call_id=call_id
)
case _:
self._logger.warn(
"Attempted to send top level message on closed session"
)
return rx_queue
# Channel events are processed via structural pattern matching, so it would be nice
# to define them as tuples to make them as lightweight as possible at runtime.
# Unfortunately, mypy doesn't cleanly support exhaustiveness checking if we define
# them that way: https://github.com/python/mypy/issues/16650
# Instead, we define our own generic base type and define subclasses for each event
@dataclass(frozen=True, slots=True)
class ChannelRxEvent(Generic[T]):
arg: T
class ChannelFinishedEvent(ChannelRxEvent[None]):
pass
ChannelCommonRxEvent: TypeAlias = ChannelFinishedEvent
TRxEvent = TypeVar("TRxEvent", bound=ChannelRxEvent[Any], contravariant=True)
class ChannelEndpoint(Generic[T, TRxEvent, TWireFormat], ABC):
"""Base class for defining API channel endpoints."""
# Overridden in concrete subclasses
_API_ENDPOINT = ""
_NOTICE_PREFIX = ""
def __init__(
self, creation_params: LMStudioStruct[TWireFormat] | DictObject
) -> None:
"""Initialize API channel endpoint handler."""
if not isinstance(creation_params, LMStudioStruct):
creation_params = LMStudioStruct._from_any_api_dict(creation_params)
self._creation_params = creation_params.to_dict()
# Channel processing state tracking
self._is_finished = False
self._result: T | None = None
self._logger = logger = new_logger(type(self).__name__)
logger.update_context(endpoint=self._API_ENDPOINT)
@property
def api_endpoint(self) -> str:
"""Get the API endpoint for this channel."""
return self._API_ENDPOINT
@property
def creation_params(self) -> TWireFormat:
"""Get the creation parameters for this channel."""
return self._creation_params
@property
def notice_prefix(self) -> str:
"""Get the logging notification prefix for this channel."""
return self._NOTICE_PREFIX
@property
def is_finished(self) -> bool:
"""Indicate whether further message reception on the channel is needed."""
return self._is_finished
def _set_result(self, result: T) -> ChannelFinishedEvent:
# Note: errors are raised immediately when handling the relevant message
# rather than only being reported when the result is accessed
self._logger.debug("Channel result received, closing channel")
self._is_finished = True
self._result = result
return ChannelFinishedEvent(None)
def result(self) -> T:
"""Read the result from a finished channel."""
if not self._is_finished:
raise LMStudioRuntimeError(
"Attempted to read result from an active channel."
)
assert self._result is not None
return self._result
def report_unknown_message(self, unknown_message: Any) -> None:
# By default, each unique unknown message will be reported once per
# calling code location, NOT per channel instance. This is reasonable,
# since it generally indicates an SDK/server version compatibility issue,
# not a problem with any specific instance
# Potentially useful warnings filters:
# * Always show: "always:LMStudioUnknownMessageWarning"
# * Never show: "ignore:LMStudioUnknownMessageWarning"
# * Client exception: "error:LMStudioUnknownMessageWarning"
warnings.warn(
f"{self._NOTICE_PREFIX} unexpected message contents: {unknown_message!r}",
LMStudioUnknownMessageWarning,
stacklevel=2, # Handle based on caller's code location
)
# See ChannelHandler below for more details on the routing of received messages
# from the API namespace websocket to the corresponding channel instances
# Called in the foreground channel event processing context
# to convert server messages to Rx events for further processing
# Defined as an iterable, since one server message may trigger multiple Rx events
@abstractmethod
def iter_message_events(self, contents: DictObject | None) -> Iterable[TRxEvent]:
raise NotImplementedError
# Called in the foreground channel event processing context
# to process Rx events and invoke any registered callbacks
@abstractmethod
def handle_rx_event(self, event: TRxEvent) -> None:
raise NotImplementedError
# Convenience API to simply process all received events
# without inspecting them individually
def handle_message_events(self, contents: DictObject | None) -> None:
for event in self.iter_message_events(contents):
self.handle_rx_event(event)
class ModelDownloadProgressEvent(ChannelRxEvent[DownloadProgressUpdate]):
pass
class ModelDownloadFinalizeEvent(ChannelRxEvent[None]):
pass
ModelDownloadRxEvent: TypeAlias = (
ModelDownloadProgressEvent | ModelDownloadFinalizeEvent | ChannelCommonRxEvent
)
DownloadProgressCallback: TypeAlias = Callable[[DownloadProgressUpdate], Any]
DownloadFinalizedCallback: TypeAlias = Callable[[], Any]
class ModelDownloadEndpoint(
ChannelEndpoint[str, ModelDownloadRxEvent, DownloadModelChannelRequestDict]
):
"""API channel endpoint for downloading available models."""
_API_ENDPOINT = "downloadModel"
_NOTICE_PREFIX = "Model download"
def __init__(
self,
download_identifier: str,
on_progress: DownloadProgressCallback | None = None,
on_finalize: DownloadFinalizedCallback | None = None,
) -> None:
params = DownloadModelChannelRequest._from_api_dict(
{"downloadIdentifier": download_identifier}
)
super().__init__(params)
self._download_identifier = download_identifier
self._on_progress = on_progress
self._on_finalize = on_finalize
def iter_message_events(
self, contents: DictObject | None
) -> Iterable[ModelDownloadRxEvent]:
match contents:
case None:
raise LMStudioChannelClosedError(
"Server failed to complete model download."
)
case {
"type": "downloadProgress",
"update": {
"downloadedBytes": downloaded_bytes,
"totalBytes": total_bytes,
"speedBytesPerSecond": speed_bytes_per_second,
},
}:
if self._on_progress is not None:
yield ModelDownloadProgressEvent(
DownloadProgressUpdate(
downloaded_bytes=downloaded_bytes,
total_bytes=total_bytes,
speed_bytes_per_second=speed_bytes_per_second,
),
)
case {"type": "startFinalizing"}:
if self._on_finalize is not None:
yield ModelDownloadFinalizeEvent(None)
case {"type": "success", "defaultIdentifier": str(default_identifier)}:
yield self._set_result(default_identifier)
case unmatched:
self.report_unknown_message(unmatched)
def handle_rx_event(self, event: ModelDownloadRxEvent) -> None:
match event:
case ModelDownloadProgressEvent(update):
self._report_progress(update)
case ModelDownloadFinalizeEvent(_):
self._finalize_download()
case ChannelFinishedEvent(_):
pass
case _:
assert_never(event)
def _report_progress(self, progress: DownloadProgressUpdate) -> None:
# This event is only emitted if a callback is registered
assert self._on_progress is not None
err_msg = (
f"Progress callback failed when downloading {self._download_identifier!r}"
)
with sdk_callback_invocation(err_msg, self._logger):
self._on_progress(progress)
def _finalize_download(self) -> None:
# This event is only emitted if a callback is registered
assert self._on_finalize is not None
err_msg = (
f"Download finalization callback failed for {self._download_identifier!r}"
)
with sdk_callback_invocation(err_msg, self._logger):
self._on_finalize()
class ModelLoadingProgressEvent(ChannelRxEvent[float]):
pass
ModelLoadingRxEvent: TypeAlias = ModelLoadingProgressEvent | ChannelCommonRxEvent
ModelLoadingCallback: TypeAlias = Callable[[float], Any]
class _ModelLoadingEndpoint(
ChannelEndpoint[ModelLoadResult, ModelLoadingRxEvent, TWireFormat]
):
def __init__(
self,
model_key: str,
creation_params: LMStudioStruct[TWireFormat] | DictObject,
on_load_progress: ModelLoadingCallback | None = None,
) -> None:
super().__init__(creation_params)
self._logger.update_context(model_key=model_key)
self._model_key = model_key
self._on_load_progress = on_load_progress
self._last_progress_event = -1.0
def _update_progress(self, progress: float) -> Iterable[ModelLoadingProgressEvent]:
if progress <= self._last_progress_event:
# Disallow going backwards or repeating values
return
self._last_progress_event = progress
if self._on_load_progress is not None:
yield ModelLoadingProgressEvent(progress)
def iter_message_events(
self, contents: DictObject | None
) -> Iterable[ModelLoadingRxEvent]:
if self._is_finished:
raise LMStudioClientError("Attempted to update a completed channel.")
match contents:
case None:
raise LMStudioChannelClosedError(
"Server failed to load requested model."
)