-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontrol_web.py
More file actions
1639 lines (1474 loc) · 57.4 KB
/
Copy pathcontrol_web.py
File metadata and controls
1639 lines (1474 loc) · 57.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
"""Local FastAPI control panel for llama.cpp Control Deck."""
from __future__ import annotations
import argparse
import contextlib
import json
import os
import re
import shlex
import shutil
import sys
import threading
import time
from copy import deepcopy
from pathlib import Path
from typing import Any
import uvicorn
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from starlette.concurrency import run_in_threadpool
import llama_cpp_release
from config import (
APP_DIR,
LOG_DIR,
PROFILE_ORDER,
RUNTIME_KEYS,
_has_llama_shared_libraries,
active_profile,
apply_runtime_autodetect,
get_profile,
load_config,
save_config,
)
from llama_server_manager import LlamaServerManager, ProcessResult, tail_file
TEMPLATES_DIR = APP_DIR / "templates"
STATIC_DIR = APP_DIR / "static"
INDEX_TEMPLATE = TEMPLATES_DIR / "index.html"
STATE_PLACEHOLDER = "__CONTROL_DECK_INITIAL_STATE__"
SUPPORTED_LANGUAGES = {"ru", "en"}
DEFAULT_WEB_HOST = "127.0.0.1"
DEFAULT_WEB_PORT = 8765
PATH_KINDS = {"python", "llama_server", "directory", "library_dir", "model", "mmproj", "preset", "file"}
PRESET_SUFFIXES = {".json", ".yaml", ".yml"}
PYTHON_NAME_RE = re.compile(r"^python(?:\d+(?:\.\d+)?)?(?:\.exe)?$")
LLAMA_SERVER_NAMES = {"llama-server", "llama-server.exe"}
REQUIRED_I18N_KEYS = [
"app_title",
"advanced",
"auto_detect",
"beginner",
"copy",
"devices",
"download",
"download_status",
"diagnostics",
"language",
"logs",
"model",
"openai_url",
"proxy",
"refresh",
"restart",
"save",
"server",
"start",
"status",
"stop",
"runtime_updates",
"services",
"add_service",
"edit",
"duplicate",
"delete",
"command_preview",
"theme",
"offline",
"online",
"profile",
"port",
"proxy_port",
"target_openai_url",
"ollama_url",
"runtime",
"check_release",
"python",
"llama_server",
"working_dir",
"ld_library_path",
"context",
"gpu_layers",
"threads",
"extra_args",
"latest",
"close",
"cancel",
"validate",
"create_and_start",
"choose_path",
"start_location",
"up",
"current_path",
"open",
"select_this_folder",
"select",
"first_run_setup",
"first_run_intro",
"detect_runtime_step",
"select_model_step",
"save_start_step",
"choose_model",
"continue",
"basic",
"performance",
"network",
"name",
"alias",
"enabled",
"model_gguf",
"mmproj",
"models_dir",
"models_preset",
"main_gpu",
"batch_threads",
"batch",
"micro_batch",
"flash_attention",
"split_mode",
"tensor_split",
"api_key",
"openai_url_preview",
"router_max_models",
"mmap",
"mlock",
"web_ui",
"continuous_batching",
"slots",
"router_autoload",
"start_selected",
"stop_selected",
"undo_delete",
"host",
"metrics",
"browse",
]
I18N: dict[str, dict[str, str]] = {
"ru": {
"app_title": "llama.cpp Control Deck",
"advanced": "Расширенные настройки",
"auto_detect": "Найти окружение",
"beginner": "Быстрый запуск",
"copy": "Копировать",
"devices": "GPU / устройства",
"download": "Скачать llama-server",
"download_status": "Статус скачивания",
"diagnostics": "Диагностика",
"language": "Язык",
"logs": "Логи",
"model": "Модель GGUF",
"openai_url": "OpenAI URL",
"proxy": "Ollama proxy",
"refresh": "Обновить",
"restart": "Перезапустить",
"save": "Сохранить",
"server": "Сервер",
"start": "Запустить",
"status": "Статус",
"stop": "Остановить",
"runtime_updates": "Окружение и обновления",
"services": "Сервисы",
"add_service": "Добавить сервис",
"edit": "Редактировать",
"duplicate": "Дублировать",
"delete": "Удалить",
"command_preview": "Команда запуска",
"theme": "Тема",
"offline": "Связь с панелью потеряна. Повторяем подключение...",
"online": "Связь восстановлена.",
"profile": "Профиль",
"port": "Порт",
"proxy_port": "Порт proxy",
"target_openai_url": "Целевой OpenAI URL",
"ollama_url": "Ollama URL",
"runtime": "Окружение",
"check_release": "Проверить release",
"python": "Python",
"llama_server": "llama-server",
"working_dir": "Рабочая папка",
"ld_library_path": "LD library path",
"context": "Контекст",
"gpu_layers": "GPU слои",
"threads": "Потоки",
"extra_args": "Доп. аргументы",
"latest": "Последние",
"close": "Закрыть",
"cancel": "Отмена",
"validate": "Проверить",
"create_and_start": "Создать и запустить",
"choose_path": "Выбрать путь",
"start_location": "Старт",
"up": "Вверх",
"current_path": "Текущий путь",
"open": "Открыть",
"select_this_folder": "Выбрать эту папку",
"select": "Выбрать",
"first_run_setup": "Первый запуск",
"first_run_intro": "Выполните эти шаги, чтобы запустить первую локальную модель.",
"detect_runtime_step": "Найти Python, llama-server, рабочую папку и библиотеки.",
"select_model_step": "Выбрать локальный файл модели .gguf.",
"save_start_step": "Сохранить настройки и запустить OpenAI-compatible endpoint.",
"choose_model": "Выбрать модель",
"continue": "Продолжить",
"basic": "Основное",
"performance": "Производительность",
"network": "Сеть",
"name": "Название",
"alias": "Alias",
"enabled": "Включено",
"model_gguf": "Модель .gguf",
"mmproj": "MMProj",
"models_dir": "Папка моделей",
"models_preset": "Preset моделей",
"main_gpu": "Основная GPU",
"batch_threads": "Потоки batch",
"batch": "Batch",
"micro_batch": "Micro-batch",
"flash_attention": "Flash attention",
"split_mode": "Split mode",
"tensor_split": "Tensor split",
"api_key": "API key",
"openai_url_preview": "Предпросмотр OpenAI URL",
"router_max_models": "Макс. моделей router",
"mmap": "mmap",
"mlock": "mlock",
"web_ui": "web UI",
"continuous_batching": "continuous batching",
"slots": "slots",
"router_autoload": "router autoload",
"start_selected": "Запустить выбранные",
"stop_selected": "Остановить выбранные",
"undo_delete": "Отменить удаление",
"host": "Host",
"metrics": "metrics",
"browse": "Выбрать",
},
"en": {
"app_title": "llama.cpp Control Deck",
"advanced": "Advanced settings",
"auto_detect": "Auto-detect runtime",
"beginner": "Quick start",
"copy": "Copy",
"devices": "GPU / devices",
"download": "Download llama-server",
"download_status": "Download status",
"diagnostics": "Diagnostics",
"language": "Language",
"logs": "Logs",
"model": "GGUF model",
"openai_url": "OpenAI URL",
"proxy": "Ollama proxy",
"refresh": "Refresh",
"restart": "Restart",
"save": "Save",
"server": "Server",
"start": "Start",
"status": "Status",
"stop": "Stop",
"runtime_updates": "Runtime & updates",
"services": "Services",
"add_service": "Add service",
"edit": "Edit",
"duplicate": "Duplicate",
"delete": "Delete",
"command_preview": "Command preview",
"theme": "Theme",
"offline": "Connection to the control panel was lost. Retrying...",
"online": "Connection restored.",
"profile": "Profile",
"port": "Port",
"proxy_port": "Proxy port",
"target_openai_url": "Target OpenAI URL",
"ollama_url": "Ollama URL",
"runtime": "Runtime",
"check_release": "Check release",
"python": "Python",
"llama_server": "llama-server",
"working_dir": "Working dir",
"ld_library_path": "LD library path",
"context": "Context",
"gpu_layers": "GPU layers",
"threads": "Threads",
"extra_args": "Extra args",
"latest": "Latest",
"close": "Close",
"cancel": "Cancel",
"validate": "Validate",
"create_and_start": "Create and start",
"choose_path": "Choose path",
"start_location": "Start",
"up": "Up",
"current_path": "Current path",
"open": "Open",
"select_this_folder": "Select this folder",
"select": "Select",
"first_run_setup": "First run setup",
"first_run_intro": "Follow these steps to start your first local model.",
"detect_runtime_step": "Find Python, llama-server, working directory, and libraries.",
"select_model_step": "Choose a local .gguf model file.",
"save_start_step": "Save settings and launch the OpenAI-compatible endpoint.",
"choose_model": "Choose model",
"continue": "Continue",
"basic": "Basic",
"performance": "Performance",
"network": "Network",
"name": "Name",
"alias": "Alias",
"enabled": "Enabled",
"model_gguf": "Model .gguf",
"mmproj": "MMProj",
"models_dir": "Models dir",
"models_preset": "Models preset",
"main_gpu": "Main GPU",
"batch_threads": "Batch threads",
"batch": "Batch",
"micro_batch": "Micro-batch",
"flash_attention": "Flash attention",
"split_mode": "Split mode",
"tensor_split": "Tensor split",
"api_key": "API key",
"openai_url_preview": "OpenAI URL preview",
"router_max_models": "Router max models",
"mmap": "mmap",
"mlock": "mlock",
"web_ui": "web UI",
"continuous_batching": "continuous batching",
"slots": "slots",
"router_autoload": "router autoload",
"start_selected": "Start selected",
"stop_selected": "Stop selected",
"undo_delete": "Undo delete",
"host": "Host",
"metrics": "metrics",
"browse": "Browse",
},
}
INSTANCE_EDIT_KEYS = {
"id",
"name",
"enabled",
"profile",
"model_path",
"mmproj_path",
"models_dir",
"models_preset",
"host",
"port",
"alias",
"api_key",
"n_ctx",
"n_threads",
"n_threads_batch",
"n_gpu_layers",
"main_gpu",
"split_mode",
"tensor_split",
"n_batch",
"n_ubatch",
"flash_attn",
"models_max",
"extra_args",
"use_mmap",
"use_mlock",
"webui",
"cont_batching",
"metrics",
"slots",
"models_autoload",
}
RESTART_REQUIRED_KEYS = {
"profile",
"model_path",
"mmproj_path",
"models_dir",
"models_preset",
"host",
"port",
"api_key",
"n_ctx",
"n_threads",
"n_threads_batch",
"n_gpu_layers",
"main_gpu",
"split_mode",
"tensor_split",
"n_batch",
"n_ubatch",
"flash_attn",
"models_max",
"extra_args",
"use_mmap",
"use_mlock",
"webui",
"cont_batching",
"metrics",
"slots",
"models_autoload",
}
_DOWNLOAD_LOCK = threading.Lock()
_DOWNLOAD_JOB: dict[str, Any] = {
"status": "idle",
"message": "No download running.",
"started_at": None,
"finished_at": None,
"lines": [],
"result": None,
"error": "",
}
class ConfigPatch(BaseModel):
ui_language: str | None = None
active_profile: str | None = None
runtime: dict[str, Any] | None = None
profile: dict[str, Any] | None = None
proxy: dict[str, Any] | None = None
class InstancePayload(BaseModel):
instance: dict[str, Any]
start: bool = False
class InstanceReorderPayload(BaseModel):
ids: list[str]
class PathValidatePayload(BaseModel):
path: str
kind: str
class ClientErrorPayload(BaseModel):
message: str
source: str | None = "web"
stack: str | None = ""
class _ProgressWriter:
def __init__(self, limit: int = 120):
self.limit = limit
self._buffer = ""
def write(self, text: str) -> int:
self._buffer += text
while "\n" in self._buffer:
line, self._buffer = self._buffer.split("\n", 1)
line = line.strip()
if line:
_download_log(line)
return len(text)
def flush(self) -> None:
line = self._buffer.strip()
if line:
_download_log(line)
self._buffer = ""
def _download_log(message: str) -> None:
with _DOWNLOAD_LOCK:
_DOWNLOAD_JOB["message"] = message
lines = list(_DOWNLOAD_JOB.get("lines") or [])
lines.append(message)
_DOWNLOAD_JOB["lines"] = lines[-120:]
def _set_download_job(**updates: Any) -> None:
with _DOWNLOAD_LOCK:
_DOWNLOAD_JOB.update(updates)
def download_job_status() -> dict[str, Any]:
with _DOWNLOAD_LOCK:
return deepcopy(_DOWNLOAD_JOB)
def _manager() -> LlamaServerManager:
return LlamaServerManager(load_config())
def _language(config: dict[str, Any]) -> str:
language = str(config.get("ui_language") or "ru").lower()
return language if language in SUPPORTED_LANGUAGES else "ru"
def _coerce_port(value: Any, default: int) -> int:
try:
port = int(value)
except (TypeError, ValueError):
return default
return port if 1 <= port <= 65535 else default
def _connect_host(host: str) -> str:
host = (host or "127.0.0.1").strip()
return "127.0.0.1" if host in {"0.0.0.0", "::", "*"} else host
def _result_payload(result: ProcessResult, next_action: str = "") -> dict[str, Any]:
payload: dict[str, Any] = {
"ok": result.ok,
"message": result.message,
"next_action": next_action,
}
details = {
"pid": result.pid,
"log_path": result.log_path,
"command": result.command,
}
payload["details"] = {key: value for key, value in details.items() if value}
return payload
def _friendly_status(kind: str, status: dict[str, Any], language: str) -> str:
if language == "en":
if status.get("running") and status.get("healthy"):
return f"{kind} is ready"
if status.get("running"):
return f"{kind} is starting or not healthy yet"
return f"{kind} is stopped"
if status.get("running") and status.get("healthy"):
return f"{kind} готов к работе"
if status.get("running"):
return f"{kind} запускается или пока не отвечает"
return f"{kind} остановлен"
def _path_exists(value: Any, directory: bool = False) -> bool:
text = str(value or "").strip()
if not text:
return False
path = Path(text).expanduser()
return path.is_dir() if directory else path.exists()
def _expanded_user_path(value: Any) -> Path:
return Path(str(value or "")).expanduser()
def _existing_directory(value: Any) -> Path | None:
text = str(value or "").strip()
if not text:
return None
path = _expanded_user_path(text)
if path.is_file():
path = path.parent
return path.resolve() if path.is_dir() else None
def _dedupe_existing_dirs(paths: list[Any]) -> list[Path]:
results: list[Path] = []
seen: set[str] = set()
for value in paths:
directory = _existing_directory(value)
if not directory:
continue
key = str(directory)
if key in seen:
continue
seen.add(key)
results.append(directory)
return results
def _path_roots(config: dict[str, Any]) -> list[dict[str, str]]:
profile = active_profile(config)
roots: list[tuple[str, Any]] = [
("Project", APP_DIR),
("Project parent", APP_DIR.parent),
("Home", Path.home()),
]
for label, key in [
("Python directory", "python_path"),
("llama-server directory", "llama_server_binary"),
("Working directory", "llama_server_cwd"),
("LD library path", "llama_server_library_path"),
]:
roots.append((label, config.get(key)))
for label, key in [
("Current model directory", "model_path"),
("Current models directory", "models_dir"),
("Current preset directory", "models_preset"),
]:
roots.append((label, profile.get(key)))
for instance in config.get("instances") or []:
name = str(instance.get("name") or instance.get("id") or "Service")
for key in ["model_path", "mmproj_path", "models_dir", "models_preset"]:
roots.append((f"{name} {key}", instance.get(key)))
for item in (os.environ.get("LLAMA_CPP_SEARCH_ROOTS") or "").split(os.pathsep):
if item.strip():
roots.append(("Search root", item))
result: list[dict[str, str]] = []
seen: set[str] = set()
for label, value in roots:
directory = _existing_directory(value)
if not directory:
continue
path = str(directory)
if path in seen:
continue
seen.add(path)
result.append({"label": label, "path": path})
return result
def _is_executable(path: Path) -> bool:
return path.is_file() and os.access(path, os.X_OK)
def _selectable_for_kind(path: Path, kind: str) -> bool:
if kind not in PATH_KINDS:
return False
if kind in {"directory", "library_dir"}:
return path.is_dir()
if path.is_dir():
return False
suffix = path.suffix.lower()
name = path.name.lower()
if kind == "python":
return _is_executable(path) and bool(PYTHON_NAME_RE.match(name))
if kind == "llama_server":
return _is_executable(path) and name in LLAMA_SERVER_NAMES
if kind in {"model", "mmproj"}:
return path.is_file() and suffix == ".gguf"
if kind == "preset":
return path.is_file() and suffix in PRESET_SUFFIXES
if kind == "file":
return path.is_file()
return False
def _entry_allowed(path: Path, kind: str) -> bool:
if not path.exists():
return False
if path.is_dir():
return True
if kind in {"directory", "library_dir"}:
return False
return _selectable_for_kind(path, kind)
def _path_entry(path: Path, kind: str) -> dict[str, Any]:
entry: dict[str, Any] = {
"name": path.name,
"path": str(path),
"type": "directory" if path.is_dir() else "file",
"selectable": _selectable_for_kind(path, kind),
}
if path.is_file():
with contextlib.suppress(OSError):
entry["size"] = path.stat().st_size
entry["executable"] = _is_executable(path)
if path.is_dir() and kind == "library_dir":
entry["has_llama_libs"] = _has_llama_shared_libraries(path)
return entry
def list_path_entries(path: Any, kind: str) -> dict[str, Any]:
if kind not in PATH_KINDS:
raise HTTPException(status_code=400, detail="Unsupported path picker kind")
directory = _expanded_user_path(path)
if directory.is_file():
directory = directory.parent
if not directory.is_dir():
raise HTTPException(status_code=404, detail="Directory not found")
directory = directory.resolve()
entries: list[dict[str, Any]] = []
with os.scandir(directory) as iterator:
for item in iterator:
entry_path = Path(item.path)
if not _entry_allowed(entry_path, kind):
continue
entries.append(_path_entry(entry_path, kind))
entries.sort(key=lambda entry: (entry["type"] != "directory", entry["name"].lower()))
parent = directory.parent if directory.parent != directory else None
return {
"path": str(directory),
"parent": str(parent) if parent else "",
"entries": entries,
}
def validate_path_choice(path: Any, kind: str) -> dict[str, Any]:
if kind not in PATH_KINDS:
return {"ok": False, "message": "Unknown path type.", "details": {"kind": kind}}
text = str(path or "").strip()
if not text:
return {"ok": False, "message": "Path is empty.", "details": {"path": text, "kind": kind}}
candidate = _expanded_user_path(text)
details: dict[str, Any] = {"path": str(candidate), "kind": kind}
if not candidate.exists():
return {"ok": False, "message": "Path does not exist.", "details": details}
if kind == "library_dir":
if not candidate.is_dir():
return {"ok": False, "message": "Existing folder is required.", "details": details}
details["has_llama_libs"] = _has_llama_shared_libraries(candidate)
return {"ok": True, "message": "Path is valid.", "details": details}
if kind == "directory":
if candidate.is_dir():
return {"ok": True, "message": "Path is valid.", "details": details}
return {"ok": False, "message": "Existing folder is required.", "details": details}
if kind == "python" and not _selectable_for_kind(candidate, kind):
return {"ok": False, "message": "Executable Python path is required.", "details": details}
if kind == "llama_server" and not _selectable_for_kind(candidate, kind):
return {"ok": False, "message": "Executable llama-server path is required.", "details": details}
if kind in {"model", "mmproj"} and not _selectable_for_kind(candidate, kind):
return {"ok": False, "message": "A .gguf file is required.", "details": details}
if kind == "preset" and not _selectable_for_kind(candidate, kind):
return {"ok": False, "message": "A .json, .yaml, or .yml file is required.", "details": details}
if kind == "file" and not candidate.is_file():
return {"ok": False, "message": "Existing file is required.", "details": details}
return {"ok": True, "message": "Path is valid.", "details": details}
def validate_config(config: dict[str, Any]) -> list[dict[str, str]]:
"""Return user-facing preflight warnings without mutating config."""
warnings: list[dict[str, str]] = []
profile = active_profile(config)
profile_type = str(profile.get("profile_type") or config.get("active_profile") or "chat")
binary = str(config.get("llama_server_binary") or "").strip()
if not binary:
warnings.append(
{
"code": "missing_binary",
"message": "llama-server path is empty.",
"next_action": "Run Auto-detect runtime or download llama-server.",
}
)
elif not Path(binary).expanduser().exists() and not shutil.which(binary):
warnings.append(
{
"code": "missing_binary",
"message": f"llama-server not found: {binary}",
"next_action": "Run Auto-detect runtime or select the correct binary.",
}
)
model_path = str(profile.get("model_path") or "").strip()
if profile_type != "router":
if not model_path:
warnings.append(
{
"code": "missing_model",
"message": "Model .gguf is not selected.",
"next_action": "Set the GGUF model path, then save.",
}
)
elif not Path(model_path).expanduser().exists():
warnings.append(
{
"code": "missing_model",
"message": f"Model file not found: {model_path}",
"next_action": "Select an existing .gguf model file.",
}
)
for key in ["llama_server_cwd", "llama_server_library_path"]:
value = str(config.get(key) or "").strip()
if value and not _path_exists(value, directory=True):
warnings.append(
{
"code": f"missing_{key}",
"message": f"{key} directory does not exist: {value}",
"next_action": "Run Auto-detect runtime or select an existing directory.",
}
)
host = str(profile.get("host") or "127.0.0.1")
port = profile.get("port") or 8081
try:
port_number = int(port)
if port_number < 1 or port_number > 65535:
raise ValueError
except (TypeError, ValueError):
warnings.append(
{
"code": "invalid_port",
"message": f"Port is invalid: {port}",
"next_action": "Use a number from 1 to 65535.",
}
)
port_number = 8081
numeric_fields = [
"n_ctx",
"n_threads",
"n_threads_batch",
"main_gpu",
"n_batch",
"n_ubatch",
"models_max",
]
for key in numeric_fields:
value = profile.get(key)
if value in {None, ""}:
continue
try:
int(value)
except (TypeError, ValueError):
warnings.append(
{
"code": f"invalid_{key}",
"message": f"{key} must be a number.",
"next_action": "Fix the value in Advanced settings.",
}
)
gpu_layers = profile.get("n_gpu_layers")
if gpu_layers not in {None, "", "all"}:
try:
int(gpu_layers)
except (TypeError, ValueError):
warnings.append(
{
"code": "invalid_n_gpu_layers",
"message": "GPU layers must be a number or 'all'.",
"next_action": "Use 'all' or a numeric layer count.",
}
)
manager = _manager()
server = manager.server_status()
server_owns_port = (
server.get("running")
and str(server.get("host") or host) == host
and int(server.get("port") or 0) == port_number
)
owner = None if server_owns_port else manager.port_owner(host, port_number)
if owner:
warnings.append(
{
"code": "busy_port",
"message": f"Port {port_number} is busy.",
"next_action": "Choose another port or stop the process that uses it.",
}
)
return warnings
def _safe_instance_id(value: str) -> str:
safe = "".join(ch if ch.isalnum() or ch in "_.-" else "-" for ch in value.strip().lower())
safe = "-".join(part for part in safe.split("-") if part)
return safe or "service"
def _instance_id(instance: dict[str, Any]) -> str:
raw = str(instance.get("id") or instance.get("name") or "").strip()
if raw:
return raw
return f"{instance.get('profile') or 'chat'}-{instance.get('port') or '8081'}"
def _instance_index(config: dict[str, Any], instance_id: str) -> int | None:
for index, instance in enumerate(config.get("instances") or []):
if _instance_id(instance) == instance_id:
return index
fallback = f"{instance.get('profile') or 'chat'}-{instance.get('port') or '8081'}"
if fallback == instance_id:
return index
return None
def _next_free_port(config: dict[str, Any], start: int = 8081) -> int:
used = set()
manager = LlamaServerManager(config)
for instance in config.get("instances") or []:
try:
used.add(int(instance.get("port")))
except (TypeError, ValueError):
pass
for profile in (config.get("profiles") or {}).values():
try:
used.add(int(profile.get("port")))
except (TypeError, ValueError):
pass
for port in range(start, 65536):
if port in used:
continue
if not manager.port_owner("127.0.0.1", port):
return port
return start
def _service_defaults(config: dict[str, Any], profile_name: str = "chat") -> dict[str, Any]:
profile_name = profile_name if profile_name in PROFILE_ORDER else "chat"
profile = deepcopy(get_profile(config, profile_name))
port = _next_free_port(config, _coerce_port(profile.get("port"), 8081))
service_id = _unique_instance_id(config, f"{profile_name}-{port}")
name = f"{profile_name.capitalize()} {port}"
defaults = {key: profile.get(key) for key in INSTANCE_EDIT_KEYS if key in profile}
defaults.update(
{
"id": service_id,
"name": name,
"enabled": True,
"profile": profile_name,
"host": profile.get("host") or "127.0.0.1",
"port": port,
"alias": profile.get("alias") or f"local-{profile_name}",
}
)
return _clean_instance(defaults)
def _unique_instance_id(config: dict[str, Any], base: str) -> str:
existing = {_instance_id(instance) for instance in config.get("instances") or []}
safe = _safe_instance_id(base)
if safe not in existing:
return safe
suffix = 2
while f"{safe}-{suffix}" in existing:
suffix += 1
return f"{safe}-{suffix}"
def _clean_instance(instance: dict[str, Any]) -> dict[str, Any]:
cleaned = {key: value for key, value in instance.items() if key in INSTANCE_EDIT_KEYS}
cleaned["id"] = _safe_instance_id(str(cleaned.get("id") or cleaned.get("name") or "service"))
cleaned["name"] = str(cleaned.get("name") or cleaned["id"]).strip()
cleaned["profile"] = str(cleaned.get("profile") or "chat").strip() or "chat"
cleaned["enabled"] = bool(cleaned.get("enabled", True))
for key in [
"use_mmap",
"use_mlock",
"webui",
"cont_batching",
"metrics",
"slots",
"models_autoload",
]:
if key in cleaned:
cleaned[key] = bool(cleaned[key])
return cleaned
def _port_owner_is_self(
config: dict[str, Any],
instance_id: str | None,
host: str,
port: int,
) -> bool:
if not instance_id:
return False
status = LlamaServerManager(config).instance_status({"id": instance_id, "host": host, "port": port})
return bool(status.get("running")) and int(status.get("port") or 0) == port
def validate_instance(
config: dict[str, Any],
instance: dict[str, Any],
original_id: str | None = None,
) -> list[dict[str, str]]:
warnings: list[dict[str, str]] = []
cleaned = _clean_instance(instance)
instance_id = cleaned.get("id", "")
profile_name = str(cleaned.get("profile") or "")
if not cleaned.get("name"):
warnings.append({"code": "missing_name", "message": "Service name is required.", "next_action": "Enter a name."})
if profile_name not in PROFILE_ORDER:
warnings.append(
{
"code": "invalid_profile",
"message": f"Unknown service type: {profile_name}",
"next_action": "Choose a supported profile.",
}
)
existing_ids = {_instance_id(item) for item in config.get("instances") or []}
if instance_id in existing_ids and instance_id != original_id:
warnings.append(
{
"code": "duplicate_id",
"message": f"Service id already exists: {instance_id}",
"next_action": "Use a different id or duplicate the service.",
}
)