-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdeno_local_llm_refiner.py
More file actions
2377 lines (2098 loc) · 84.1 KB
/
Copy pathdeno_local_llm_refiner.py
File metadata and controls
2377 lines (2098 loc) · 84.1 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
from __future__ import annotations
import base64
import hashlib
import http.client
import itertools
from io import BytesIO
import json
import logging
import os
import queue
import random
import re
import threading
import time
import urllib.parse
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
import numpy as np
from PIL import Image
try:
from comfy_execution.graph_utils import ExecutionBlocker
except Exception: # pragma: no cover - ComfyUI provides this at runtime.
class ExecutionBlocker: # type: ignore[no-redef]
def __init__(self, message):
self.message = message
try:
from aiohttp import web
from server import PromptServer
except Exception: # pragma: no cover - ComfyUI provides these at runtime.
web = None
PromptServer = None
try:
import comfy.model_management as comfy_model_management
except Exception: # pragma: no cover - ComfyUI provides this at runtime.
comfy_model_management = None
try:
from .deno_resolution_common import validate_combo_choice
except Exception: # pragma: no cover - direct import during local tests
from deno_resolution_common import validate_combo_choice
PROVIDER_OLLAMA = "Ollama"
PROVIDER_LM_STUDIO = "LM Studio"
LEGACY_PROVIDER_CUSTOM = "Custom Local Server"
PROVIDERS = [PROVIDER_OLLAMA, PROVIDER_LM_STUDIO]
OLLAMA_DEFAULT_SERVER = "http://127.0.0.1:11434"
LM_STUDIO_DEFAULT_SERVER = "http://127.0.0.1:1234/v1"
LEGACY_CUSTOM_SERVER_DEFAULT = "http://127.0.0.1:8000/v1"
MEMORY_UNLOAD_AFTER_RUN = "Unload after run"
LEGACY_MEMORY_FREE_AFTER_BATCH = "Free VRAM after batch"
MEMORY_KEEP_MINUTES = "Keep for minutes"
MEMORY_KEEP_LOADED = "Keep loaded"
MODEL_MEMORY_OPTIONS = [
MEMORY_UNLOAD_AFTER_RUN,
MEMORY_KEEP_MINUTES,
MEMORY_KEEP_LOADED,
]
MODEL_MEMORY_ALIASES = {
LEGACY_MEMORY_FREE_AFTER_BATCH: MEMORY_UNLOAD_AFTER_RUN,
}
COMFY_VRAM_AUTO = "Auto: unload only before first LLM call"
COMFY_VRAM_ALWAYS = "Always unload before each LLM call"
COMFY_VRAM_NEVER = "Never unload before LLM call"
COMFY_VRAM_POLICY_OPTIONS = [
COMFY_VRAM_AUTO,
COMFY_VRAM_ALWAYS,
COMFY_VRAM_NEVER,
]
COMFY_VRAM_POLICY_ALIASES = {
"Auto": COMFY_VRAM_AUTO,
"Always free": COMFY_VRAM_ALWAYS,
"Never free": COMFY_VRAM_NEVER,
}
_IS_CHANGED_COUNTER = itertools.count()
COMFY_VRAM_FREE_SETTLE_SECONDS = 0.6
SEED_MODE_FIXED = "fixed"
SEED_MODE_INCREMENT = "increment"
SEED_MODE_DECREMENT = "decrement"
SEED_MODE_RANDOMIZE = "randomize"
SEED_MODE_OPTIONS = [
SEED_MODE_FIXED,
SEED_MODE_INCREMENT,
SEED_MODE_DECREMENT,
SEED_MODE_RANDOMIZE,
]
SHIFTED_MODEL_WIDGET_VALUES = {
PROVIDER_OLLAMA,
PROVIDER_LM_STUDIO,
LEGACY_PROVIDER_CUSTOM,
MEMORY_UNLOAD_AFTER_RUN,
LEGACY_MEMORY_FREE_AFTER_BATCH,
MEMORY_KEEP_MINUTES,
MEMORY_KEEP_LOADED,
COMFY_VRAM_AUTO,
COMFY_VRAM_ALWAYS,
COMFY_VRAM_NEVER,
SEED_MODE_FIXED,
SEED_MODE_INCREMENT,
SEED_MODE_DECREMENT,
SEED_MODE_RANDOMIZE,
"Refresh Models",
"Stop LLM",
"Unload LLM",
"System Prompt",
"Thinking",
"Seed",
"Seed Mode",
"Model After Run",
"Unload ComfyUI Models Setting",
"ComfyUI VRAM",
"Ollama Model",
"LM Studio Model",
"Legacy Model",
"Custom Model",
"Custom Server URL",
*COMFY_VRAM_POLICY_ALIASES,
}
MISSING_SAVED_MODEL_PREFIX = "Missing saved model: "
LOCAL_HOSTS = {"127.0.0.1", "localhost", "::1", "[::1]"}
PROGRESS_EVENT = "deno-local-llm-progress"
THINK_TAG_RE = re.compile(r"<(?:think|thinking)>(.*?)</(?:think|thinking)>", re.IGNORECASE | re.DOTALL)
FINAL_PROMPT_TAG_RE = re.compile(r"<final\\?_prompt>(.*?)</final\\?_prompt>", re.IGNORECASE | re.DOTALL)
FINAL_PROMPT_MARKER_RE = re.compile(
r"FINAL\\?[_\s-]*PROMPT\\?[_\s-]*START\s*(.*?)\s*FINAL\\?[_\s-]*PROMPT\\?[_\s-]*END",
re.IGNORECASE | re.DOTALL,
)
FINAL_PROMPT_LINE_RE = re.compile(r"DENO_FINAL_PROMPT\s*:\s*([^\r\n]+)", re.IGNORECASE)
REVIEWER_PREVIEW_SUBFOLDER = "deno_llm_reviewer"
_WARM_LOCAL_LLM_KEYS: Dict[str, Optional[float]] = {}
_ACTIVE_LOCAL_LLM_KEYS: Dict[str, int] = {}
_CANCEL_LOCAL_LLM_KEYS: Set[str] = set()
_ACTIVE_LOCAL_LLM_LOCK = threading.Lock()
def _json_response(payload: Dict[str, Any], status: int = 200):
if web is None:
return {"payload": payload, "status": status}
return web.json_response(payload, status=status)
def _parse_local_llm_url(url: str) -> urllib.parse.ParseResult:
parsed = urllib.parse.urlparse(str(url or "").strip())
if parsed.scheme not in {"http", "https"}:
raise RuntimeError("Use a local http:// or https:// server URL.")
host = parsed.hostname or ""
if host.lower() not in LOCAL_HOSTS:
raise RuntimeError(
"Only local LLM servers are allowed for this DENO node. "
"Use 127.0.0.1 or localhost."
)
return parsed
def _assert_local_url(url: str) -> None:
_parse_local_llm_url(url)
def _open_local_llm_http_connection(
parsed: urllib.parse.ParseResult,
timeout: float,
) -> http.client.HTTPConnection:
host = parsed.hostname
if not host:
raise RuntimeError("Local LLM server URL is missing a host.")
port = parsed.port
connection_cls = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
return connection_cls(host, port, timeout=timeout)
def _strip_trailing_slash(url: str) -> str:
return str(url or "").strip().rstrip("/")
def _looks_like_url(value: Any) -> bool:
text = str(value or "").strip().lower()
return text.startswith(("http://", "https://"))
def _is_missing_saved_model_display(value: Any) -> bool:
return str(value or "").strip().startswith(MISSING_SAVED_MODEL_PREFIX)
def _original_model_value_from_display(value: Any) -> str:
text = str(value or "").strip()
if text.startswith(MISSING_SAVED_MODEL_PREFIX):
return text[len(MISSING_SAVED_MODEL_PREFIX):].strip()
return text
def _looks_like_shifted_model_value(value: Any) -> bool:
text = _original_model_value_from_display(value)
if not text:
return False
if _looks_like_url(text) or text in SHIFTED_MODEL_WIDGET_VALUES:
return True
if text.lower() in {"true", "false"}:
return True
return bool(re.fullmatch(r"-?\d+(?:\.\d+)?", text))
def _missing_saved_model_error(provider: str, model: Any) -> str:
model_value = _original_model_value_from_display(model)
return (
f"Saved {provider} model is not available on this PC: {model_value}. "
"Start the local LLM server and press Refresh Models, install/load that model, or choose another installed model."
)
def _shifted_model_error(action: str, model: str) -> str:
return (
f"Refresh models and select a real local LLM model before {action}. "
f"The current value looks like a shifted UI label, not a model name: {model}"
)
def _normalize_provider(provider: str) -> str:
value = str(provider or "").strip()
if value == LEGACY_PROVIDER_CUSTOM:
return PROVIDER_OLLAMA
return value if value in PROVIDERS else PROVIDER_OLLAMA
def _normalize_ollama_url(server_url: str) -> str:
url = _strip_trailing_slash(server_url or "http://127.0.0.1:11434")
_assert_local_url(url)
return url
def _normalize_lm_openai_url(server_url: str) -> str:
url = _strip_trailing_slash(server_url or "http://127.0.0.1:1234/v1")
_assert_local_url(url)
if url.endswith("/v1"):
return url
if url.endswith("/api/v1"):
return url[:-7] + "/v1"
return f"{url}/v1"
def _normalize_lm_native_url(server_url: str) -> str:
url = _strip_trailing_slash(server_url or "http://127.0.0.1:1234")
_assert_local_url(url)
if url.endswith("/v1"):
return url[:-3]
if url.endswith("/api/v1"):
return url[:-7]
return url
def _canonical_local_llm_state_url(provider: str, server_url: str) -> str:
provider = _normalize_provider(provider)
if provider == PROVIDER_OLLAMA:
url = _normalize_ollama_url(server_url)
elif provider == PROVIDER_LM_STUDIO:
url = _normalize_lm_native_url(server_url)
else:
url = _strip_trailing_slash(server_url)
parsed = urllib.parse.urlparse(url)
host = str(parsed.hostname or "").lower()
if host in {"localhost", "::1", "[::1]"}:
host = "127.0.0.1"
if not host:
return _strip_trailing_slash(url).lower()
netloc = f"{host}:{parsed.port}" if parsed.port else host
path = parsed.path.rstrip("/")
return urllib.parse.urlunparse((parsed.scheme.lower() or "http", netloc, path, "", "", ""))
def _model_unavailable_message(model: str, detail: str = "") -> str:
model_value = str(model or "").strip()
if model_value:
message = (
f"Selected local LLM model is not available: {model_value}. "
"Refresh Models and choose another model, or load this model in Ollama / LM Studio first."
)
else:
message = "Selected local LLM model is not available. Refresh Models and choose another model."
detail_value = str(detail or "").strip()
if detail_value:
message = f"{message} Server detail: {detail_value[:300]}"
return message
def _looks_like_model_unavailable_error(message: str) -> bool:
text = str(message or "").lower()
return any(
marker in text
for marker in (
"model_not_found",
"model not found",
"not found",
"not loaded",
"no such model",
"unknown model",
"model is not loaded",
)
)
def _extract_local_llm_error_detail(data: str) -> str:
text = str(data or "").strip()
if not text:
return ""
try:
payload = json.loads(text)
except Exception:
return text
error = payload.get("error") if isinstance(payload, dict) else None
if isinstance(error, dict):
return str(error.get("message") or error.get("type") or error)
if error is not None:
return str(error)
return text
def _local_llm_http_error(status: int, data: str, payload: Optional[Dict[str, Any]] = None) -> RuntimeError:
detail = _extract_local_llm_error_detail(data)
model = ""
if isinstance(payload, dict):
model = str(payload.get("model") or payload.get("instance_id") or "").strip()
if status in {400, 404, 405} and model and _looks_like_model_unavailable_error(detail):
return RuntimeError(_model_unavailable_message(model, detail))
return RuntimeError(f"Local LLM server returned HTTP {status}: {str(data or '')[:800]}")
def _http_json(
url: str,
payload: Optional[Dict[str, Any]] = None,
method: str = "GET",
timeout: float = 20.0,
) -> Dict[str, Any]:
parsed = _parse_local_llm_url(url)
path = parsed.path or "/"
if parsed.query:
path = f"{path}?{parsed.query}"
body = None if payload is None else json.dumps(payload).encode("utf-8")
headers = {"Accept": "application/json"}
if body is not None:
headers["Content-Type"] = "application/json"
connection = _open_local_llm_http_connection(parsed, timeout=timeout)
try:
connection.request(method.upper(), path, body=body, headers=headers)
response = connection.getresponse()
data = response.read().decode("utf-8", errors="replace")
if response.status >= 400:
raise _local_llm_http_error(response.status, data, payload)
except (TimeoutError, OSError, http.client.HTTPException) as exc:
raise RuntimeError(f"Could not reach local LLM server: {exc}") from exc
finally:
try:
connection.close()
except Exception:
pass
if not data.strip():
return {}
return json.loads(data)
def _http_stream_json_lines(
url: str,
payload: Dict[str, Any],
timeout: float = 600.0,
cancel_key: Optional[str] = None,
) -> Iterable[Dict[str, Any]]:
try:
for raw_line in _iter_cancellable_response_lines(url, payload, timeout=timeout, cancel_key=cancel_key):
line = raw_line.decode("utf-8", errors="replace").strip()
if not line:
continue
yield json.loads(line)
except (TimeoutError, OSError, http.client.HTTPException) as exc:
raise RuntimeError(f"Could not reach local LLM server: {exc}") from exc
def _http_stream_sse(
url: str,
payload: Dict[str, Any],
timeout: float = 600.0,
cancel_key: Optional[str] = None,
) -> Iterable[Tuple[str, Dict[str, Any]]]:
event_name = "message"
data_lines: List[str] = []
try:
for raw_line in _iter_cancellable_response_lines(url, payload, timeout=timeout, cancel_key=cancel_key):
line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
if not line:
if data_lines:
data = "\n".join(data_lines).strip()
if data and data != "[DONE]":
yield event_name, json.loads(data)
event_name = "message"
data_lines = []
continue
if line.startswith("event:"):
event_name = line.split(":", 1)[1].strip()
elif line.startswith("data:"):
data_lines.append(line.split(":", 1)[1].strip())
if data_lines:
data = "\n".join(data_lines).strip()
if data and data != "[DONE]":
yield event_name, json.loads(data)
except (TimeoutError, OSError, http.client.HTTPException) as exc:
raise RuntimeError(f"Could not reach local LLM server: {exc}") from exc
def _iter_cancellable_response_lines(
url: str,
payload: Dict[str, Any],
timeout: float = 600.0,
cancel_key: Optional[str] = None,
) -> Iterable[bytes]:
parsed = _parse_local_llm_url(url)
path = parsed.path or "/"
if parsed.query:
path = f"{path}?{parsed.query}"
connection = _open_local_llm_http_connection(parsed, timeout=timeout)
response_queue: "queue.Queue[Tuple[str, Any]]" = queue.Queue()
stop_event = threading.Event()
def reader() -> None:
try:
body = json.dumps(payload).encode("utf-8")
connection.request("POST", path, body=body, headers={"Content-Type": "application/json"})
response = connection.getresponse()
if response.status >= 400:
message = response.read().decode("utf-8", errors="replace")
raise _local_llm_http_error(response.status, message, payload)
while not stop_event.is_set():
raw_line = response.readline()
if raw_line == b"":
break
response_queue.put(("line", raw_line))
response_queue.put(("done", None))
except BaseException as exc:
if stop_event.is_set():
response_queue.put(("done", None))
else:
response_queue.put(("error", exc))
finally:
try:
connection.close()
except Exception:
pass
thread = threading.Thread(target=reader, daemon=True)
thread.start()
try:
while True:
_raise_if_local_llm_stopped(cancel_key)
try:
kind, value = response_queue.get(timeout=0.2)
except queue.Empty:
continue
_raise_if_local_llm_stopped(cancel_key)
if kind == "line":
yield value
continue
if kind == "done":
break
if kind == "error":
raise value
finally:
stop_event.set()
try:
connection.close()
except Exception:
pass
thread.join(timeout=0.1)
def _extract_scalar(value: Any, default: Any = None) -> Any:
if isinstance(value, list):
if not value:
return default
return _extract_scalar(value[0], default)
return default if value is None else value
def _extract_media(value: Any) -> Any:
if isinstance(value, list):
for item in value:
found = _extract_media(item)
if found is not None:
return found
return None
return value
def _safe_int(value: Any, default: int, minimum: int = 0, maximum: Optional[int] = None) -> int:
try:
parsed = int(float(_extract_scalar(value, default)))
except (TypeError, ValueError, OverflowError):
parsed = int(default)
parsed = max(int(minimum), parsed)
if maximum is not None:
parsed = min(int(maximum), parsed)
return parsed
def _safe_bool(value: Any, default: bool = False) -> bool:
scalar = _extract_scalar(value, default)
if isinstance(scalar, bool):
return scalar
text = str(scalar).strip().lower()
if text in {"true", "1", "yes", "on"}:
return True
if text in {"false", "0", "no", "off", ""}:
return False
return bool(default)
def _cache_array_signature(value: Any) -> Dict[str, Any]:
array = np.ascontiguousarray(value)
return {
"__array__": True,
"dtype": str(array.dtype),
"shape": list(array.shape),
"sha256": hashlib.sha256(array.tobytes()).hexdigest(),
}
def _cache_stable_value(value: Any) -> Any:
if value is None or isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, np.ndarray):
return _cache_array_signature(value)
if hasattr(value, "detach") and hasattr(value, "cpu"):
try:
return _cache_array_signature(value.detach().cpu().numpy())
except Exception:
pass
if isinstance(value, dict):
return {
str(key): _cache_stable_value(item)
for key, item in sorted(value.items(), key=lambda pair: str(pair[0]))
}
if isinstance(value, (list, tuple)):
return [_cache_stable_value(item) for item in value]
try:
json.dumps(value, sort_keys=True)
return value
except TypeError:
return {"__repr__": repr(value), "__type__": type(value).__name__}
def _local_llm_cache_key(kwargs: Dict[str, Any]) -> str:
seed_mode = _normalize_seed_mode(kwargs.get("seed_mode", SEED_MODE_FIXED))
if seed_mode == SEED_MODE_RANDOMIZE:
return f"randomize:{time.monotonic_ns()}:{next(_IS_CHANGED_COUNTER)}"
payload = {
key: _cache_stable_value(value)
for key, value in sorted(kwargs.items())
if key != "unique_id"
}
payload["seed_mode"] = seed_mode
encoded = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
return f"stable:{hashlib.sha256(encoded.encode('utf-8')).hexdigest()}"
def _normalize_model_memory(value: Any) -> str:
text = str(_extract_scalar(value, MEMORY_UNLOAD_AFTER_RUN) or MEMORY_UNLOAD_AFTER_RUN).strip()
text = MODEL_MEMORY_ALIASES.get(text, text)
return text if text in MODEL_MEMORY_OPTIONS else MEMORY_UNLOAD_AFTER_RUN
def _normalize_comfy_vram_policy(value: Any) -> str:
text = str(_extract_scalar(value, COMFY_VRAM_AUTO) or COMFY_VRAM_AUTO).strip()
text = COMFY_VRAM_POLICY_ALIASES.get(text, text)
return text if text in COMFY_VRAM_POLICY_OPTIONS else COMFY_VRAM_AUTO
def _normalize_seed_mode(value: Any) -> str:
text = str(_extract_scalar(value, SEED_MODE_FIXED) or SEED_MODE_FIXED).strip()
if text == "random":
return SEED_MODE_RANDOMIZE
return text if text in SEED_MODE_OPTIONS else SEED_MODE_FIXED
def _flatten_prompts(value: Any) -> List[str]:
if value is None:
return [""]
if isinstance(value, list):
prompts: List[str] = []
for item in value:
prompts.extend(_flatten_prompts(item))
return prompts or [""]
return [str(value)]
def _seed_for_index(seed: int, mode: str = "fixed", index: int = 0) -> int:
seed = int(seed)
mode = _normalize_seed_mode(mode)
if mode == SEED_MODE_INCREMENT:
return max(0, seed + index)
if mode == SEED_MODE_DECREMENT:
return max(0, seed - index)
if mode == SEED_MODE_RANDOMIZE:
return random.randint(0, 0xFFFFFFFF)
return max(0, seed)
def _ollama_keep_alive(model_memory: str, keep_minutes: int, is_last: bool) -> Any:
keep_minutes = max(1, int(keep_minutes))
model_memory = _normalize_model_memory(model_memory)
if model_memory == MEMORY_KEEP_LOADED:
return "-1m"
if model_memory == MEMORY_KEEP_MINUTES:
return f"{keep_minutes}m"
return "0m" if is_last else f"{keep_minutes}m"
def _lm_ttl(model_memory: str, keep_minutes: int, is_last: bool) -> int:
keep_minutes = max(1, int(keep_minutes))
model_memory = _normalize_model_memory(model_memory)
if model_memory == MEMORY_KEEP_LOADED:
return 24 * 60 * 60
if model_memory == MEMORY_KEEP_MINUTES:
return keep_minutes * 60
return 1 if is_last else max(60, keep_minutes * 60)
def _should_unload_after_run(model_memory: str, is_last: bool) -> bool:
return bool(is_last and _normalize_model_memory(model_memory) == MEMORY_UNLOAD_AFTER_RUN)
def _llm_state_key(provider: str, server_url: str, model: str) -> str:
return "|".join([
_normalize_provider(provider),
_canonical_local_llm_state_url(provider, server_url),
str(model or "").strip(),
])
def _is_local_llm_marked_warm(key: str) -> bool:
expires_at = _WARM_LOCAL_LLM_KEYS.get(key)
if key not in _WARM_LOCAL_LLM_KEYS:
return False
if expires_at is None:
return True
if time.monotonic() < expires_at:
return True
_WARM_LOCAL_LLM_KEYS.pop(key, None)
return False
def _mark_local_llm_warm(provider: str, server_url: str, model: str, model_memory: str, keep_minutes: int) -> None:
key = _llm_state_key(provider, server_url, model)
memory_value = _normalize_model_memory(model_memory)
if memory_value == MEMORY_KEEP_LOADED:
_WARM_LOCAL_LLM_KEYS[key] = None
elif memory_value == MEMORY_KEEP_MINUTES:
_WARM_LOCAL_LLM_KEYS[key] = time.monotonic() + max(1, int(keep_minutes)) * 60
else:
_WARM_LOCAL_LLM_KEYS.pop(key, None)
def _clear_local_llm_warm(provider: str, server_url: str, model: str) -> None:
_WARM_LOCAL_LLM_KEYS.pop(_llm_state_key(provider, server_url, model), None)
def _parse_llm_state_key(key: str) -> Optional[Tuple[str, str, str]]:
parts = str(key or "").split("|", 2)
if len(parts) != 3 or not parts[0] or not parts[1] or not parts[2]:
return None
return parts[0], parts[1], parts[2]
def _unload_other_warm_local_llms(provider: str, server_url: str, model: str, node_id: str) -> Dict[str, Any]:
current_key = _llm_state_key(provider, server_url, model)
unloaded: List[Dict[str, Any]] = []
errors: List[str] = []
for key in list(_WARM_LOCAL_LLM_KEYS):
if key == current_key:
continue
if not _is_local_llm_marked_warm(key):
continue
parsed = _parse_llm_state_key(key)
if parsed is None:
_WARM_LOCAL_LLM_KEYS.pop(key, None)
continue
old_provider, old_server_url, old_model = parsed
if _llm_state_key(old_provider, old_server_url, old_model) == current_key:
_WARM_LOCAL_LLM_KEYS.pop(key, None)
continue
_send_progress({
"node_id": node_id,
"status": "swapping local LLM",
"provider": provider,
"model": model,
"index": 0,
"total": 0,
"answer": "",
"thinking": f"Unloading previous kept {old_provider} model before loading {provider}.",
})
try:
result = unload_local_llm_model(old_provider, old_server_url, old_model)
if not result.get("ok"):
errors.append(str(result.get("message") or result.get("error") or result))
continue
unloaded.append({
"provider": old_provider,
"server_url": old_server_url,
"model": old_model,
"message": result.get("message", ""),
})
except RuntimeError as exc:
message = str(exc)
if "Could not reach local LLM server" in message:
_WARM_LOCAL_LLM_KEYS.pop(key, None)
unloaded.append({
"provider": old_provider,
"server_url": old_server_url,
"model": old_model,
"message": "Cleared stale warm marker because the previous local LLM server was not reachable.",
})
continue
errors.append(message)
if errors:
raise RuntimeError("Could not unload the previous kept local LLM before switching: " + "; ".join(errors))
return {
"action": "unloaded_previous" if unloaded else "none",
"current": {
"provider": provider,
"server_url": _strip_trailing_slash(server_url),
"model": model,
},
"unloaded": unloaded,
}
def _mark_local_llm_active(provider: str, server_url: str, model: str) -> str:
key = _llm_state_key(provider, server_url, model)
with _ACTIVE_LOCAL_LLM_LOCK:
_ACTIVE_LOCAL_LLM_KEYS[key] = _ACTIVE_LOCAL_LLM_KEYS.get(key, 0) + 1
return key
def _clear_local_llm_active(key: str) -> None:
with _ACTIVE_LOCAL_LLM_LOCK:
count = _ACTIVE_LOCAL_LLM_KEYS.get(key, 0)
if count <= 1:
_ACTIVE_LOCAL_LLM_KEYS.pop(key, None)
_CANCEL_LOCAL_LLM_KEYS.discard(key)
else:
_ACTIVE_LOCAL_LLM_KEYS[key] = count - 1
def _is_local_llm_active(provider: str, server_url: str, model: str) -> bool:
key = _llm_state_key(provider, server_url, model)
with _ACTIVE_LOCAL_LLM_LOCK:
return _ACTIVE_LOCAL_LLM_KEYS.get(key, 0) > 0
def _busy_unload_response(provider: str, model: str) -> Dict[str, Any]:
return {
"ok": False,
"busy": True,
"message": (
f"{provider} model is still generating: {model}. "
"Press Stop LLM first, wait for the current request to stop, then unload."
),
}
def _local_llm_stop_exception(message: str):
exc_cls = getattr(comfy_model_management, "InterruptProcessingException", None) if comfy_model_management else None
if exc_cls is not None:
return exc_cls(message)
return RuntimeError(message)
def _raise_if_local_llm_stopped(cancel_key: Optional[str] = None) -> None:
if cancel_key:
with _ACTIVE_LOCAL_LLM_LOCK:
cancelled = cancel_key in _CANCEL_LOCAL_LLM_KEYS
if cancelled:
_CANCEL_LOCAL_LLM_KEYS.discard(cancel_key)
if cancelled:
raise _local_llm_stop_exception("Local LLM generation stopped.")
if comfy_model_management is not None:
throw_if_interrupted = getattr(comfy_model_management, "throw_exception_if_processing_interrupted", None)
if callable(throw_if_interrupted):
throw_if_interrupted()
def _candidate_stop_keys(provider: str, server_url: str, model: str) -> List[str]:
provider = _normalize_provider(provider)
if provider == PROVIDER_LM_STUDIO:
native_base = _normalize_lm_native_url(server_url)
openai_base = _normalize_lm_openai_url(server_url)
return [
_llm_state_key(provider, openai_base, model),
_llm_state_key(provider, native_base, model),
]
base = _normalize_ollama_url(server_url)
return [_llm_state_key(PROVIDER_OLLAMA, base, model)]
def stop_local_llm_generation(provider: str, server_url: str, model: str) -> Dict[str, Any]:
provider = _normalize_provider(provider)
model = str(model or "").strip()
if not model:
raise RuntimeError("Select a local LLM model before stopping.")
if _looks_like_shifted_model_value(model):
raise RuntimeError(_shifted_model_error("stopping", model))
keys = _candidate_stop_keys(provider, server_url, model)
with _ACTIVE_LOCAL_LLM_LOCK:
active_keys = [key for key in keys if _ACTIVE_LOCAL_LLM_KEYS.get(key, 0) > 0]
for key in active_keys:
_CANCEL_LOCAL_LLM_KEYS.add(key)
if not active_keys:
return {
"ok": False,
"stopping": False,
"message": f"No active {provider} request matched {model}.",
}
return {
"ok": True,
"stopping": True,
"message": f"Stop requested for {provider} model: {model}.",
}
def _safe_free_memory_bytes() -> Optional[int]:
if comfy_model_management is None:
return None
try:
device = comfy_model_management.get_torch_device()
return int(comfy_model_management.get_free_memory(device))
except Exception:
return None
def _loaded_comfy_model_count() -> Optional[int]:
if comfy_model_management is None:
return None
try:
return len(comfy_model_management.loaded_models())
except Exception:
return None
def _free_comfy_vram_for_local_llm() -> Dict[str, Any]:
info: Dict[str, Any] = {
"available": comfy_model_management is not None,
"before_free_bytes": _safe_free_memory_bytes(),
"before_loaded_models": _loaded_comfy_model_count(),
"after_free_bytes": None,
"after_loaded_models": None,
"settle_seconds": COMFY_VRAM_FREE_SETTLE_SECONDS,
}
if comfy_model_management is None:
info["reason"] = "ComfyUI model management is not available in this runtime."
return info
try:
comfy_model_management.unload_all_models()
comfy_model_management.soft_empty_cache(force=True)
time.sleep(COMFY_VRAM_FREE_SETTLE_SECONDS)
comfy_model_management.soft_empty_cache(force=True)
info["after_free_bytes"] = _safe_free_memory_bytes()
info["after_loaded_models"] = _loaded_comfy_model_count()
except Exception as exc:
info["error"] = str(exc)
logging.warning("DENO Local LLM could not free ComfyUI VRAM before LLM call: %s", exc)
return info
def _prepare_comfy_vram_before_llm(
provider: str,
server_url: str,
model: str,
model_memory: str,
keep_minutes: int,
comfy_vram_policy: str,
node_id: str,
) -> Dict[str, Any]:
policy = _normalize_comfy_vram_policy(comfy_vram_policy)
key = _llm_state_key(provider, server_url, model)
if policy == COMFY_VRAM_NEVER:
return {"policy": policy, "action": "skipped", "reason": "disabled"}
if policy == COMFY_VRAM_AUTO and _is_local_llm_marked_warm(key):
return {"policy": policy, "action": "skipped", "reason": "local LLM is already marked loaded"}
if policy == COMFY_VRAM_AUTO and _is_provider_model_loaded(provider, server_url, model):
_mark_local_llm_warm(provider, server_url, model, model_memory, keep_minutes)
return {"policy": policy, "action": "skipped", "reason": "local LLM is already loaded by provider"}
_send_progress({
"node_id": node_id,
"status": "freeing ComfyUI VRAM",
"provider": provider,
"model": model,
"index": 0,
"total": 0,
"answer": "",
"thinking": "ComfyUI diffusion models are being unloaded before the local LLM request.",
})
info = _free_comfy_vram_for_local_llm()
info["policy"] = policy
info["action"] = "freed" if info.get("available") and not info.get("error") else "attempted"
return info
def _split_thinking_tags(answer: str, thinking: str) -> Tuple[str, str]:
extracted = [match.group(1).strip() for match in THINK_TAG_RE.finditer(answer or "")]
if extracted:
answer = THINK_TAG_RE.sub("", answer or "").strip()
thinking = "\n".join(part for part in [thinking, *extracted] if str(part or "").strip()).strip()
answer = re.sub(r"</?(?:think|thinking)>", "", answer or "", flags=re.IGNORECASE).strip()
return answer or "", thinking or ""
def _requires_final_prompt_block(system_prompt: str) -> bool:
prompt = str(system_prompt or "").lower()
return (
("<final_prompt>" in prompt and "</final_prompt>" in prompt)
or ("final_prompt_start" in prompt and "final_prompt_end" in prompt)
or ("deno_final_prompt" in prompt)
)
def _is_valid_final_prompt_candidate(candidate: str) -> bool:
text = str(candidate or "").strip()
if not text:
return False
lower = text.lower()
rejected_fragments = (
"your final image prompt here",
"the app will pass only",
"the app will keep only",
"return exactly",
"do not explain",
"downstream",
)
return not any(fragment in lower for fragment in rejected_fragments)
def _extract_final_prompt_block(answer: str, require: bool = False) -> str:
text = answer or ""
for pattern in (FINAL_PROMPT_LINE_RE, FINAL_PROMPT_TAG_RE, FINAL_PROMPT_MARKER_RE):
matches = [match.group(1).strip() for match in pattern.finditer(text)]
matches = [match for match in matches if _is_valid_final_prompt_candidate(match)]
if matches:
return matches[-1]
if require:
raise RuntimeError(
"The local model did not return the required Prompt Only final prompt block. "
"Use a model that follows the Prompt Only preset, or remove the block requirement."
)
return text
def _requires_final_prompt_tags(system_prompt: str) -> bool:
return _requires_final_prompt_block(system_prompt)
def _extract_final_prompt_tags(answer: str, require: bool = False) -> str:
return _extract_final_prompt_block(answer, require=require)
def _raise_if_thinking_only_result(answer: str, thinking: str) -> None:
if str(answer or "").strip() or not str(thinking or "").strip():
return
raise RuntimeError(
"The local model returned thinking text but no final result. "
"Turn Thinking off, or ask the model to write a final answer after thinking."
)
def _ensure_ollama_model_stays_loaded(
base: str,
model: str,
keep_alive: Any,
node_id: str,
index: int,
total: int,
) -> Dict[str, Any]:
keep_alive_value = str(keep_alive)
if keep_alive_value in ("0", "0m", "0s"):
return {"checked": False, "reason": "unload_requested"}
was_loaded = _ollama_is_model_loaded(base, model)
if not was_loaded:
_send_progress({
"node_id": node_id,
"status": "keeping local LLM loaded",
"provider": PROVIDER_OLLAMA,
"model": model,
"index": index,
"total": total,
"answer": "",